Try..Catch 不能捕获的错误有哪些?注意事项又有哪些?

开发 前端
今天的内容中,我们来学习一下使用try、catch、finally和throw进行错误处理。我们还会讲一下 JS 中内置的错误对象(Error, SyntaxError, ReferenceError等)以及如何定义自定义错误。

[[373698]]

本文已经原作者 Ashish Lahoti 授权翻译。

今天的内容中,我们来学习一下使用try、catch、finally和throw进行错误处理。我们还会讲一下 JS 中内置的错误对象(Error, SyntaxError, ReferenceError等)以及如何定义自定义错误。

1.使用 try..catch..finally..throw

在 JS 中处理错误,我们主要使用try、catch、finally和throw关键字。

  • try块包含我们需要检查的代码
  • 关键字throw用于抛出自定义错误
  • catch块处理捕获的错误
  • finally 块是最终结果无论如何,都会执行的一个块,可以在这个块里面做一些需要善后的事情

1.1 try

每个try块必须与至少一个catch或finally块,否则会抛出SyntaxError错误。

我们单独使用try块进行验证:

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

1.2 try..catch

建议将try与catch块一起使用,它可以优雅地处理try块抛出的错误。

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

1.2.1 try..catch 与 无效代码

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

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

1.2.2 try..catch 与 异步代码

同样,try..catch无法捕获在异步代码中引发的异常,例如setTimeout:

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

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

  1. ➤ ⓧ Uncaught ReferenceError: noSuchVariable is not defined 

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

  1. setTimeout(function() { 
  2.   try { 
  3.     noSuchVariable; 
  4.   } catch(err) { 
  5.     console.log("error is caught here!"); 
  6.   } 
  7. }, 1000); 

1.2.3 嵌套 try..catch

我们还可以使用嵌套的try和catch块向上抛出错误,如下所示:

  1. try { 
  2.   try { 
  3.     throw new Error('Error while executing the inner code'); 
  4.   } catch (err) { 
  5.     throw err; 
  6.   } 
  7. } catch (err) { 
  8.   console.log("Error caught by outer block:"); 
  9.   console.error(err.message); 
  1. Error caught by outer block: 
  2. ➤ ⓧ Error while executing the code 

1.3 try..finally

不建议仅使用 try..finally 而没有 catch 块,看看下面会发生什么:

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

这里注意两件事:

  • 即使从try块抛出错误后,也会执行finally块
  • 如果没有catch块,错误将不能被优雅地处理,从而导致未捕获的错误

1.4 try..catch..finally

建议使用try...catch块和可选的finally块。

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

这里还要注意两件事:

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

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

  1. try { 
  2.   openFile(file); 
  3.   readFile(file); 
  4. } catch (err) { 
  5.   console.error(err.message); 
  6. } finally { 
  7.   closeFile(file); 

1.5 throw

throw语句用于引发异常。

 

  1. throw <expression> 
  1. // throw primitives and functions 
  2. throw "Error404"
  3. throw 42; 
  4. throw true
  5. throw {toString: function() { return "I'm an object!"; } }; 
  6.  
  7. // throw error object 
  8. throw new Error('Error while executing the code'); 
  9. throw new SyntaxError('Something is wrong with the syntax'); 
  10. throw new ReferenceError('Oops..Wrong reference'); 
  11.  
  12. // throw custom error object 
  13. function ValidationError(message) { 
  14.   this.message = message; 
  15.   this.name = 'ValidationError'
  16. throw new ValidationError('Value too high'); 

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

对于异步代码的错误处理可以Promise和async await。

2.1 Promise 中的 then..catch

我们可以使用then()和catch()链接多个 Promises,以处理链中单个 Promise 的错误,如下所示:

  1. Promise.resolve(1) 
  2.   .then(res => { 
  3.       console.log(res);  // 打印 '1' 
  4.  
  5.       throw new Error('something went wrong');  // throw error 
  6.  
  7.       return Promise.resolve(2);  // 这里不会被执行 
  8.   }) 
  9.   .then(res => { 
  10.       // 这里也不会执行,因为错误还没有被处理 
  11.       console.log(res);     
  12.   }) 
  13.   .catch(err => { 
  14.       console.error(err.message);  // 打印 'something went wrong' 
  15.       return Promise.resolve(3); 
  16.   }) 
  17.   .then(res => { 
  18.       console.log(res);  // 打印 '3' 
  19.   }) 
  20.   .catch(err => { 
  21.       // 这里不会被执行 
  22.       console.error(err); 
  23.   }) 

我们来看一个更实际的示例,其中我们使用fetch调用API,该 API 返回一个promise对象,我们使用catch块优雅地处理 API 失败。

  1. function handleErrors(response) { 
  2.     if (!response.ok) { 
  3.         throw Error(response.statusText); 
  4.     } 
  5.     return response; 
  6.  
  7. fetch("http://httpstat.us/500"
  8.     .then(handleErrors) 
  9.     .then(response => console.log("ok")) 
  10.     .catch(error => console.log("Caught", error)); 
  1. Caught Error: Internal Server Error 
  2.     at handleErrors (<anonymous>:3:15) 

2.2 try..catch 和 async await

在 async await 中 使用try..catch 比较容易:

  1. (async function() { 
  2.     try { 
  3.         await fetch("http://httpstat.us/500"); 
  4.     } catch (err) { 
  5.         console.error(err.message); 
  6.     } 
  7. })(); 

让我们看同一示例,其中我们使用fetch调用API,该API返回一个promise对象, 我们使用try..catch块优雅地处理API失败。

  1. function handleErrors(response) { 
  2.     if (!response.ok) { 
  3.         throw Error(response.statusText); 
  4.     } 
  5.  
  6. (async function() { 
  7.     try { 
  8.       let response = await fetch("http://httpstat.us/500"); 
  9.       handleErrors(response); 
  10.       let data = await response.json(); 
  11.       return data; 
  12.     } catch (error) { 
  13.         console.log("Caught", error) 
  14.     } 
  15. })(); 
  1. Caught Error: Internal Server Error 
  2.     at handleErrors (<anonymous>:3:15) 
  3.     at <anonymous>:11:7 

3. JS 中的内置错误

3.1 Error

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

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

我们创建一个Error 对象,并查看它的名称和消息属性:

  1. const err = new Error('Error while executing the code'); 
  2.  
  3. console.log("name:", err.name); 
  4. console.log("message:", err.message); 
  5. console.log("stack:", err.stack); 
  1. name: Error 
  2. message: Error while executing the code 
  3. stack: Error: Error while executing the code 
  4.     at <anonymous>:1:13 

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

3.2 EvalError

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

3.3 RangeError

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

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

3.4 ReferenceError

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

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

3.5 SyntaxError

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

  1. ➤ function() { return 'Hi!' } 
  2. ⓧ Uncaught SyntaxError: Function statements require a function name 
  3.  
  4. ➤ 1 = 1 
  5. ⓧ Uncaught SyntaxError: Invalid left-hand side in assignment 
  6.  
  7. ➤ JSON.parse("{ x }"); 
  8. ⓧ Uncaught SyntaxError: Unexpected token x in JSON at position 2 

3.6 TypeError

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

  1. ➤ 1(); 
  2. ⓧ Uncaught TypeError: 1 is not a function 
  3.  
  4. ➤ null.name
  5. ⓧ Uncaught TypeError: Cannot read property 'name' of null 

3.7 URIError

如果以错误的方式使用全局 URI 方法,则会抛出URIError。

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

4. 定义并抛出自定义错误我们也可以用这种方式定义自定义错误。

  1. class CustomError extends Error { 
  2.   constructor(message) { 
  3.     super(message); 
  4.     this.name = "CustomError"
  5.   }  
  6. }; 
  7.  
  8. const err = new CustomError('Custom error while executing the code'); 
  9.  
  10. console.log("name:", err.name); 
  11. console.log("message:", err.message); 
  1. name: CustomError 
  2. message: Custom error while executing the code 

我们还可以进一步增强CustomError对象以包含错误代码

  1. class CustomError extends Error { 
  2.   constructor(message, code) { 
  3.     super(message); 
  4.     this.name = "CustomError"
  5.     this.code = code; 
  6.   }  
  7. }; 
  8.  
  9. const err = new CustomError('Custom error while executing the code'"ERROR_CODE"); 
  10.  
  11. console.log("name:", err.name); 
  12. console.log("message:", err.message); 
  13. console.log("code:", err.code); 
  1. name: CustomError 
  2. message: Custom error while executing the code 
  3. code: ERROR_CODE 

在try..catch块中使用它:

  1. try{ 
  2.   try { 
  3.     null.name
  4.   }catch(err){ 
  5.     throw new CustomError(err.message, err.name);  //message, code 
  6.   } 
  7. }catch(err){ 
  8.   console.log(err.name, err.code, err.message); 

CustomError TypeError Cannot read property 'name' of null

本文转载自微信公众号「大迁世界」,可以通过以下二维码关注。转载本文请联系大迁世界公众号。

 

责任编辑:武晓燕 来源: 大迁世界
相关推荐

2010-05-07 10:19:48

Oracle 注意事项

2020-09-27 07:48:40

不用try catch

2022-06-30 13:41:44

SQL 语句group by

2022-07-14 08:02:02

NPM依赖治理

2010-07-30 13:28:10

2022-03-10 23:12:12

云计算数据管理架构

2011-05-06 14:05:56

投影机

2010-07-30 10:11:05

DB2临时表

2011-05-26 11:22:04

SEO

2022-07-15 07:20:42

数字化智能运维

2021-07-30 11:00:02

iOS苹果系统

2011-04-27 16:16:46

投影机

2023-09-07 07:53:21

JavaScriptGoRust

2019-09-25 07:39:24

移动端PC端表单

2023-01-26 19:52:30

2021-01-28 17:25:38

安全优先事项安全威胁网络安全

2009-12-15 17:47:17

VSIP

2010-10-08 08:59:26

2010-11-26 16:27:01

MySQL使用变量

2011-09-26 11:02:10

点赞
收藏

51CTO技术栈公众号