假设以下代码:
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_error_state' 替换为 dbCall 的返回错误。
如果你想直接抛出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 正确使用 block 级变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43720039/