假设以下代码:
let test = dbCall();
console.log(test);
现在,我想将dbcall包装在try catch中。哪种方法更好:
let test = null;
try{
test = dbCall();
} catch(e) {
console.log(e);
}
console.log(test);
try{
var test = dbCall();
} catch(e) {
console.log(e);
}
console.log(test);
最佳答案
如果要返回句柄并引发自定义错误:
var test = dbCall();
try {
if(test == <dbCall_error_state>) throw "Custom error here.";
}
catch(e) {
alert("Error: " + e);
}
PS:您需要用dbCall的返回错误替换'dbCall_error_state'。
如果要直接抛出dbCall()返回的错误,请遵循ECMAScript规范:
try {
dbCall(); // may throw three types of exceptions
} catch (e) {
if (e instanceof TypeError) {
// statements to handle TypeError exceptions
} else if (e instanceof RangeError) {
// statements to handle RangeError exceptions
} else if (e instanceof EvalError) {
// statements to handle EvalError exceptions
} else {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
alert("Error: " + e); // or alert it
}
}
您可以在此处查看有关此信息的详细信息:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/try...catch
关于javascript - js如何通过try catch正确使用块级变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43720039/