「这是我参与11月更文挑战的第11天,活动详情查看:2021最后一次更文挑战」
作者: Ashish Lahoti 译者:前端很美 来源:codingnconcepts
3.js内置的错误
3.1Error
js内置的Error对象通常有try抛出catch捕捉。
Error对象有以下属性
- name: 是错误的名字,如“Error”, “SyntaxError”, “ReferenceError”等等
- message: 是错误详细信息
- stack: 是用于调试目的的错误堆栈。 来创建一个对象看看有哪些属性
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
js以下内置的错误对象都继承自Error对象。
3.2EvalError
EvalError 不在当前ECMAScript规范中使用,因此不会被运行时抛出. 但是对象本身仍然与规范的早期版本向后兼容.
3.3RangeError
数值超出范围会抛出RangeError错误。
➤ [].length = -1
ⓧ Uncaught RangeError: Invalid array length
3.4ReferenceError
引用未定义的变量时引发ReferenceError。
➤ x = x + 1;
ⓧ Uncaught ReferenceError: x is not defined
3.5SyntaxError
发生了错误的语法时,将抛出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.6TypeError
当值不是预期的类型时,将抛出TypeError。
➤ 1();
ⓧ Uncaught TypeError: 1 is not a function
➤ null.name;
ⓧ Uncaught TypeError: Cannot read property 'name' of null
3.7URIError
当全局函数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
我们还可以进一步增强自定义错误类型,比如加入错误码。
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