JS Error

🌙
手机阅读
本文目录结构

通过 Error 的构造器可以创建一个错误对象。当运行时错误产生时,Error 的实例对象会被抛出。Error 对象也可用于用户自定义的异常的基础对象。下面列出了各种内建的标准错误类型。

语法

new Error([message[, fileName[,lineNumber]]])

参数

message

可选。人类可阅读的错误描述信息。

fileName

可选。被创建的 Error 对象的 fileName 属性值。默认是调用 Error 构造器代码所在的文件 的名字。

lineNumber

可选。被创建的 Error 对象的 lineNumber 属性值。默认是调用 Error 构造器代码所在的文件的行号。

描述

当代码运行时的发生错误,会创建新的 Error 对象,并将其抛出。

该页面描述了 Error 对象自身的使用,以及其构造函数的使用。关于 Error 实例的内部属性和方法,请看 Error.prototype。

作为函数使用

当像函数一样使用 Error 时 – 如果没有 new,它将返回一个 Error 对象。所以, 仅仅调用 Error 将产生与通过 new 关键字构造 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 类型

除了通用的 Error 构造函数外,JavaScript 还有 6 个其他类型的错误构造函数。更多客户端异常,详见 Exception Handling Statements。

EvalError

创建一个 error 实例,表示错误的原因:与 eval() 有关。

InternalError

创建一个代表 Javascript 引擎内部错误的异常抛出的实例。 如:“递归太多”.

RangeError

创建一个 error 实例,表示错误的原因:数值变量或参数超出其有效范围。

ReferenceError

创建一个 error 实例,表示错误的原因:无效引用。

SyntaxError

创建一个 error 实例,表示错误的原因:eval() 在解析代码的过程中发生的语法错误。

TypeError

创建一个 error 实例,表示错误的原因:变量或参数不属于有效类型。

URIError

创建一个 error 实例,表示错误的原因:给 encodeURI() 或 decodeURl() 传递的参数无效。

属性

Error.prototype

允许添加属性到 Error 实例。

方法

全局 Error 对象自身不包含任何方法,但从原型链中继承了一些方法。

Error 实例

All Error instances and instances of non-generic errors inherit from Error.prototype. As with all constructor functions, you can use the prototype of the constructor to add properties or methods to all instances created with that constructor.

属性

Standard properties

Error.prototype.constructor

Specifies the function that created an instance’s prototype.

Error.prototype.message

Error message.

Error.prototype.name

Error name.

Vendor-specific extensions

Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Microsoft

Error.prototype.description

Error description. Similar to message.

Error.prototype.number

Error number.

Mozilla

Error.prototype.fileName

Path to file that raised this error.

Error.prototype.lineNumber

Line number in file that raised this error.

Error.prototype.columnNumber

Column number in line that raised this error.

Error.prototype.stack

Stack trace.

方法

Error.prototype.toSource()

Returns a string containing the source of the specified Error object; you can use this value to create a new object. Overrides the Object.prototype.toSource() method.

Error.prototype.toString()

Returns a string representing the specified object. Overrides the Object.prototype.toString() method.

例子

抛出一个基本错误

通常你会使用 throw 关键字来抛出你创建的 Error 对象。可以使用 try…catch 结构来处理异常:

try {
    throw new Error("Whoops!");
} catch (e) {
    alert(e.name + ": " + e.message);
}

处理一个特定错误

你可以通过判断异常的类型来特定处理某一类的异常,即判断 constructor 属性,当使用现代 Javascript 引擎时,可使用 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 来检查某个异常的类型。这种需求的通用解决方法如下。

注意,在 FireFox 中抛出自定义类型的异常会显示不正确的行号和文件名。

参考 “What’s a good way to extend Error in JavaScript?” discussion on Stackoverflow.

// 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) {
  console.log(e.name);     // 'MyError'
  console.log(e.message);  // 'custom message'
}

规范

Specification Status Comment
ECMAScript 1st Edition. Standard Initial definition. Implemented in JavaScript 1.1.
ECMAScript 5.1 (ECMA-262) Error Standard
ECMAScript 2015 (6th Edition, ECMA-262) Error Standard
ECMAScript Latest Draft (ECMA-262) Error Draft

AXIHE / 精选资源

浏览全部教程

面试题

学习网站

前端培训
自己甄别

前端书籍

关于朱安邦

我叫 朱安邦,阿西河的站长,在杭州。

以前是一名平面设计师,后来开始接接触前端开发,主要研究前端技术中的JS方向。

业余时间我喜欢分享和交流自己的技术,欢迎大家关注我的 Bilibili

关注我: Github / 知乎

于2021年离开前端领域,目前重心放在研究区块链上面了

我叫朱安邦,阿西河的站长

目前在杭州从事区块链周边的开发工作,机械专业,以前从事平面设计工作。

2014年底脱产在老家自学6个月的前端技术,自学期间几乎从未出过家门,最终找到了满意的前端工作。更多>

于2021年离开前端领域,目前从事区块链方面工作了