通过Error的构造器可以创建一个错误对象。当运行时错误产生时,Error的实例对象会被抛出。Error对象也可用于用户自定义的异常的基础对象。
// this:const x = Error('I was created using a function call!');// has the same functionality as this:const y = new Error('I was constructed via the "new" keyword!');
Error 类型
EvalError创建一个error实例,表示错误的原因:与 eval() 有关。**`
RangeError创建一个error实例,表示错误的原因:数值变量或参数超出其有效范围。ReferenceError创建一个error实例,表示错误的原因:无效引用。SyntaxError创建一个error实例,表示错误的原因:eval()在解析代码的过程中发生的语法错误。TypeError创建一个error实例,表示错误的原因:变量或参数不属于有效类型。URIError创建一个error实例,表示错误的原因:给 encodeURI()或 decodeURl()传递的参数无效。
例子
抛出一个基本错误
try {throw new Error("Whoops!");} catch (e) {alert(e.name + ": " + e.message);}
处理一个特定错误
你可以通过判断异常的类型来特定处理某一类的异常,即判断 instanceof 关键字:
try {foo.bar();} catch (e) {if (e instanceof EvalError) {alert(e.name + ": " + e.message);} else if (e instanceof RangeError) {alert(e.name + ": " + e.message);}// ... etc}
自定义异常类型
你可能希望自定义基于Error的异常类型,使得你能够 throw new MyError() 并可以使用 instanceof MyError 来检查某个异常的类型. 这种需求的通用解决方法如下.
// Create a new object, that prototypally inherits from the Error constructor.function MyError(message) {this.name = 'MyError';this.message = message || 'Default Message';this.stack = (new Error()).stack;}MyError.prototype = Object.create(Error.prototype);MyError.prototype.constructor = MyError;try {throw new MyError();} catch (e) {console.log(e.name); // 'MyError'console.log(e.message); // 'Default Message'}try {throw new MyError('custom message');} catch (e) {if (e instanceof MyError)console.log(e.name); // 'MyError'console.log(e.message); // 'custom message'}
