关于javascript:trycatch-不能捕获的错误有哪些注意事项又有哪些

作者:Ashish Lahoti
译者:前端小智
起源:codingnconcept

点赞再看,微信搜寻【大迁世界】关注这个没有大厂背景,但有着一股向上踊跃心态人。本文 GitHub https://github.com/qq44924588… 上曾经收录,文章的已分类,也整顿了很多我的文档,和教程材料。**

最近开源了一个 Vue 组件,还不够欠缺,欢送大家来一起欠缺它,也心愿大家能给个 star 反对一下,谢谢各位了。

github 地址:https://github.com/qq44924588…

明天的内容中,咱们来学习一下应用trycatchfinallythrow进行错误处理。咱们还会讲一下 JS 中内置的谬误对象(Error, SyntaxError, ReferenceError等)以及如何定义自定义谬误。

1.应用 try..catch..finally..throw

在 JS 中处理错误,咱们次要应用trycatchfinallythrow关键字。

  • try块蕴含咱们须要查看的代码
  • 关键字throw用于抛出自定义谬误
  • catch块解决捕捉的谬误
  • finally 块是最终后果无论如何,都会执行的一个块,能够在这个块外面做一些须要善后的事件

1.1 try

每个try块必须与至多一个catchfinally块,否则会抛出SyntaxError谬误。

咱们独自应用try块进行验证:

try {
  throw new Error('Error while executing the code');
}
ⓧ Uncaught SyntaxError: Missing catch or finally after try

1.2 try..catch

倡议将trycatch块一起应用,它能够优雅地解决try块抛出的谬误。

try {
  throw new Error('Error while executing the code');
} catch (err) {
  console.error(err.message);
}
➤ ⓧ Error while executing the code

1.2.1 try..catch 与 有效代码

try..catch 无奈捕捉有效的 JS 代码,例如try块中的以下代码在语法上是谬误的,但它不会被catch块捕捉。

try {
  ~!$%^&*
} catch(err) {
  console.log("这里不会被执行");
}
➤ ⓧ Uncaught SyntaxError: Invalid or unexpected token

1.2.2 try..catch 与 异步代码

同样,try..catch无奈捕捉在异步代码中引发的异样,例如setTimeout

try {
  setTimeout(function() {
    noSuchVariable;   // undefined variable
  }, 1000);
} catch (err) {
  console.log("这里不会被执行");
}

未捕捉的ReferenceError将在1秒后引发:

➤ ⓧ Uncaught ReferenceError: noSuchVariable is not defined

所以 ,咱们应该在异步代码外部应用 try..catch 来处理错误:

setTimeout(function() {
  try {
    noSuchVariable;
  } catch(err) {
    console.log("error is caught here!");
  }
}, 1000);

1.2.3 嵌套 try..catch

咱们还能够应用嵌套的trycatch块向上抛出谬误,如下所示:

try {
  try {
    throw new Error('Error while executing the inner code');
  } catch (err) {
    throw err;
  }
} catch (err) {
  console.log("Error caught by outer block:");
  console.error(err.message);
}
Error caught by outer block:
➤ ⓧ Error while executing the code

1.3 try..finally

不倡议仅应用 try..finally 而没有 catch 块,看看上面会产生什么:

try {
  throw new Error('Error while executing the code');
} finally {
  console.log('finally');
}
finally
➤ ⓧ Uncaught Error: Error while executing the code

这里留神两件事:

  • 即便从try块抛出谬误后,也会执行finally
  • 如果没有catch块,谬误将不能被优雅地解决,从而导致未捕捉的谬误

1.4 try..catch..finally

倡议应用try...catch块和可选的finally块。

try {
  console.log("Start of try block");
  throw new Error('Error while executing the code');
  console.log("End of try block -- never reached");
} catch (err) {
  console.error(err.message);
} finally {
  console.log('Finally block always run');
}
console.log("Code execution outside try-catch-finally block continue..");
Start of try block
➤ ⓧ Error while executing the code
Finally block always run
Code execution outside try-catch-finally block continue..

这里还要留神两件事:

  • try块中抛出谬误后往后的代码不会被执行了
  • 即便在try块抛出谬误之后,finally块依然执行

finally块通常用于清理资源或敞开流,如下所示:

try {
  openFile(file);
  readFile(file);
} catch (err) {
  console.error(err.message);
} finally {
  closeFile(file);
}

1.5 throw

throw语句用于引发异样。

throw <expression>
// throw primitives and functions
throw "Error404";
throw 42;
throw true;
throw {toString: function() { return "I'm an object!"; } };

// throw error object
throw new Error('Error while executing the code');
throw new SyntaxError('Something is wrong with the syntax');
throw new ReferenceError('Oops..Wrong reference');

// throw custom error object
function ValidationError(message) {
  this.message = message;
  this.name = 'ValidationError';
}
throw new ValidationError('Value too high');

2. 异步代码中的错误处理

对于异步代码的错误处理能够Promiseasync await

2.1 Promise 中的 then..catch

咱们能够应用then()catch()链接多个 Promises,以解决链中单个 Promise 的谬误,如下所示:

Promise.resolve(1)
  .then(res => {
      console.log(res);  // 打印 '1'

      throw new Error('something went wrong');  // throw error

      return Promise.resolve(2);  // 这里不会被执行
  })
  .then(res => {
      // 这里也不会执行,因为谬误还没有被解决
      console.log(res);    
  })
  .catch(err => {
      console.error(err.message);  // 打印 'something went wrong'
      return Promise.resolve(3);
  })
  .then(res => {
      console.log(res);  // 打印 '3'
  })
  .catch(err => {
      // 这里不会被执行
      console.error(err);
  })

咱们来看一个更理论的示例,其中咱们应用fetch调用API,该 API 返回一个promise对象,咱们应用catch块优雅地解决 API 失败。

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

fetch("http://httpstat.us/500")
    .then(handleErrors)
    .then(response => console.log("ok"))
    .catch(error => console.log("Caught", error));
Caught Error: Internal Server Error
    at handleErrors (<anonymous>:3:15)

2.2 try..catchasync await

async await 中 应用 try..catch 比拟容易:

(async function() {
    try {
        await fetch("http://httpstat.us/500");
    } catch (err) {
        console.error(err.message);
    }
})();

让咱们看同一示例,其中咱们应用fetch调用API,该API返回一个promise对象, 咱们应用try..catch块优雅地解决API失败。

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
}

(async function() {
    try {
      let response = await fetch("http://httpstat.us/500");
      handleErrors(response);
      let data = await response.json();
      return data;
    } catch (error) {
        console.log("Caught", error)
    }
})();
Caught Error: Internal Server Error
    at handleErrors (<anonymous>:3:15)
    at <anonymous>:11:7

3. JS 中的内置谬误

3.1 Error

JavaScript 有内置的谬误对象,它通常由try块抛出,并在catch块中捕捉,Error 对象蕴含以下属性:

  • name:是谬误的名称,例如 “Error”, “SyntaxError”, “ReferenceError” 等。
  • message:无关谬误详细信息的音讯。
  • stack:是用于调试目标的谬误的堆栈跟踪。

咱们创立一个Error 对象,并查看它的名称和音讯属性:

const err = new Error('Error while executing the code');

console.log("name:", err.name);
console.log("message:", err.message);
console.log("stack:", err.stack);
name: Error
message: Error while executing the code
stack: Error: Error while executing the code
    at <anonymous>:1:13

JavaScript 有以下内置谬误,这些谬误是从 Error 对象继承而来的

3.2 EvalError

EvalError 示意对于全局eval()函数的谬误,这个异样不再由 JS 抛出,它的存在是为了向后兼容。

3.3 RangeError

当值超出范围时,将引发RangeError

➤ [].length = -1
ⓧ Uncaught RangeError: Invalid array length

3.4 ReferenceError

当援用一个不存在的变量时,将引发 ReferenceError

➤ x = x + 1;
ⓧ Uncaught ReferenceError: x is not defined

3.5 SyntaxError

当你在 JS 代码中应用任何谬误的语法时,都会引发SyntaxError

➤ function() { return 'Hi!' }
ⓧ Uncaught SyntaxError: Function statements require a function name

➤ 1 = 1
ⓧ Uncaught SyntaxError: Invalid left-hand side in assignment

➤ JSON.parse("{ x }");
ⓧ Uncaught SyntaxError: Unexpected token x in JSON at position 2

3.6 TypeError

如果该值不是预期的类型,则抛出TypeError

➤ 1();
ⓧ Uncaught TypeError: 1 is not a function

➤ null.name;
ⓧ Uncaught TypeError: Cannot read property 'name' of null

3.7 URIError

如果以谬误的形式应用全局 URI 办法,则会抛出URIError

➤ decodeURI("%%%");
ⓧ Uncaught URIError: URI malformed

4. 定义并抛出自定义谬误

咱们也能够用这种形式定义自定义谬误。

class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "CustomError";
  } 
};

const err = new CustomError('Custom error while executing the code');

console.log("name:", err.name);
console.log("message:", err.message);
name: CustomError
message: Custom error while executing the code

咱们还能够进一步加强CustomError对象以蕴含错误代码

class CustomError extends Error {
  constructor(message, code) {
    super(message);
    this.name = "CustomError";
    this.code = code;
  } 
};

const err = new CustomError('Custom error while executing the code', "ERROR_CODE");

console.log("name:", err.name);
console.log("message:", err.message);
console.log("code:", err.code);
name: CustomError
message: Custom error while executing the code
code: ERROR_CODE

try..catch块中应用它:

try{
  try {
    null.name;
  }catch(err){
    throw new CustomError(err.message, err.name);  //message, code
  }
}catch(err){
  console.log(err.name, err.code, err.message);
}

CustomError TypeError Cannot read property ‘name’ of null

我是小智,咱们下期见!


代码部署后可能存在的BUG没法实时晓得,预先为了解决这些BUG,花了大量的工夫进行log 调试,这边顺便给大家举荐一个好用的BUG监控工具 Fundebug。

原文:https://codings.com/javascrip…

交换

文章每周继续更新,能够微信搜寻「 大迁世界 」第一工夫浏览和催更(比博客早一到两篇哟),本文 GitHub https://github.com/qq449245884/xiaozhi 曾经收录,整顿了很多我的文档,欢送Star和欠缺,大家面试能够参照考点温习,另外关注公众号,后盾回复福利,即可看到福利,你懂的。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理