做者:Ashish Lahoti
译者:前端小智
来源:codingnconcept
点赞再看,微信搜索
【大迁世界】,B站关注【
前端小智】这个没有大厂背景,但有着一股向上积极心态人。本文
GitHub
https://github.com/qq44924588... 上已经收录,文章的已分类,也整理了不少个人文档,和教程资料。**
最近开源了一个 Vue 组件,还不够完善,欢迎你们来一块儿完善它,也但愿你们能给个 star 支持一下,谢谢各位了。javascript
github 地址:https://github.com/qq44924588...前端
今天的内容中,咱们来学习一下使用try
、catch
、finally
和throw
进行错误处理。咱们还会讲一下 JS 中内置的错误对象(Error
, SyntaxError
, ReferenceError
等)以及如何定义自定义错误。vue
在 JS 中处理错误,咱们主要使用try
、catch
、finally
和throw
关键字。java
try
块包含咱们须要检查的代码throw
用于抛出自定义错误catch
块处理捕获的错误finally
块是最终结果不管如何,都会执行的一个块,能够在这个块里面作一些须要善后的事情try
每一个try
块必须与至少一个catch
或finally
块,不然会抛出SyntaxError
错误。git
咱们单独使用try
块进行验证:github
try { throw new Error('Error while executing the code'); }
ⓧ Uncaught SyntaxError: Missing catch or finally after try
try..catch
建议将try
与catch
块一块儿使用,它能够优雅地处理try
块抛出的错误。面试
try { throw new Error('Error while executing the code'); } catch (err) { console.error(err.message); }
➤ ⓧ Error while executing the code
try..catch
与 无效代码try..catch
没法捕获无效的 JS 代码,例如try
块中的如下代码在语法上是错误的,但它不会被catch
块捕获。express
try { ~!$%^&* } catch(err) { console.log("这里不会被执行"); }
➤ ⓧ Uncaught SyntaxError: Invalid or unexpected token
try..catch
与 异步代码一样,try..catch
没法捕获在异步代码中引起的异常,例如setTimeout
:json
try { setTimeout(function() { noSuchVariable; // undefined variable }, 1000); } catch (err) { console.log("这里不会被执行"); }
未捕获的ReferenceError
将在1秒后引起:promise
➤ ⓧ Uncaught ReferenceError: noSuchVariable is not defined
因此 ,咱们应该在异步代码内部使用 try..catch
来处理错误:
setTimeout(function() { try { noSuchVariable; } catch(err) { console.log("error is caught here!"); } }, 1000);
try..catch
咱们还可使用嵌套的try
和catch
块向上抛出错误,以下所示:
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
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
块,错误将不能被优雅地处理,从而致使未捕获的错误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); }
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');
对于异步代码的错误处理能够Promise
和async await
。
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)
try..catch
和 async 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
JavaScript 有内置的错误对象,它一般由try
块抛出,并在catch
块中捕获,Error 对象包含如下属性:
咱们建立一个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 对象继承而来的
EvalError 表示关于全局eval()
函数的错误,这个异常再也不由 JS 抛出,它的存在是为了向后兼容。
当值超出范围时,将引起RangeError
。
➤ [].length = -1 ⓧ Uncaught RangeError: Invalid array length
当引用一个不存在的变量时,将引起 ReferenceError。
➤ x = x + 1; ⓧ Uncaught ReferenceError: x is not defined
当你在 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
若是该值不是预期的类型,则抛出TypeError
。
➤ 1(); ⓧ Uncaught TypeError: 1 is not a function ➤ null.name; ⓧ Uncaught TypeError: Cannot read property 'name' of null
若是以错误的方式使用全局 URI 方法,则会抛出URIError
。
➤ decodeURI("%%%"); ⓧ Uncaught URIError: URI malformed
咱们也能够用这种方式定义自定义错误。
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和完善,你们面试能够参照考点复习,另外关注公众号,后台回复福利,便可看到福利,你懂的。