js如何使用try catch正确使用块级变量

时间:2017-05-01 13:38:51

标签: javascript

假设以下代码:

   let test = dbCall();
    console.log(test);

现在我想在try catch中包装dbcall。哪种方式更好:

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);

2 个答案:

答案 0 :(得分:1)

如果您想要句柄返回并抛出自定义错误:

var test = dbCall();

try { 
    if(test == <dbCall_error_state>) throw "Custom error here.";
}
catch(e) {
    alert("Error: " + e);
}

PS 您需要更换&#39; dbCall_error_state &#39;与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

答案 1 :(得分:0)

第一种选择是更恰当的方法。由于第二个选项可能会让您test is not defined。我还要确保代码永远不会到达您的示例代码&#39;或者在捕获错误的情况下进行测试记录(因此在catch块中有一个return或exit语句)。

function makeDbCall() {
  let test = null;

  try{
    test = dbCall();
  } catch(e) {
    console.log(e);
    return false;
  }

  // only a successful DB call makes it this far
  console.log(test);
  return true;
}