《现代Javascript教程》错误处理

37 阅读1分钟

错误处理,"try...catch"

try...catch同步执行 如果需要异步,必须放在异步函数内

setTimeout(()=>{
    try{//...
        // error具有任意性,但最好使用内建
        throw <error object>
    }
    //新特性:catch可以没有参数,这样同样会捕获,但是无需得知详细error
    catch(e){//...}
    finally{//...}
})

Error对象

class Error{
    name = xxx;
    message = xxx;
    //调用栈
    stack = xxx;
}

再次抛出

function readData() {
  let json = '{ "age": 30 }';

  try {
    // ...
    blabla(); // error!
  } catch (err) {
    // ...
    if (!(err instanceof SyntaxError)) {
      throw err; // 再次抛出(不知道如何处理它)
    }
  }
}

try {
  readData();
} catch (err) {
  alert( "External catch got: " + err ); // 捕获了它!
}

全局catch

例如,Node.JS 有 process.on("uncaughtException")。在浏览器中,我们可以将一个函数赋值给特殊的 window.onerror 属性,该函数将在发生未捕获的 error 时执行。

window.onerror = function(message, url, line, col, error) {
    // ...message:error 信息。
    //url:发生 error 的脚本的 URL。
    //line,col:发生 error 处的代码的行号和列号。
    //error:error 对象。
};

自定义 Error,扩展 Error

如果继承于内建Error,就可以使用instanceof Error,比较方便

let error = new Error(message);
let error = new SyntaxError(message);
let error = new ReferenceError(message);