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

语法

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

参数

message
可选。人类可阅读的错误描述信息。
fileName 
可选。被创建的Error对象的fileName属性值。默认是调用Error构造器代码所在的文件 的名字。
lineNumber 
可选。被创建的Error对象的lineNumber属性值。默认是调用Error构造器代码所在的文件的行号

描述

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

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

Used as a function

When Error is used like a function -- without new, it will return an Error object. Therefore, a mere call to Error will produce the same output that constructing an Error object via the newkeyword would.

// 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  

浏览器兼容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
Basic supportChrome Full support YesEdge Full support YesFirefox Full support 1IE Full support 6Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
prototypeChrome Full support YesEdge Full support YesFirefox Full support 1IE Full support 6Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
columnNumber
Non-standard
Chrome No support NoEdge No support NoFirefox Full support 1IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoEdge Mobile No support NoFirefox Android Full support 4Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs No support No
fileName
Non-standard
Chrome No support NoEdge No support NoFirefox Full support 1IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoEdge Mobile No support NoFirefox Android Full support 4Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs No support No
lineNumber
Non-standard
Chrome No support NoEdge No support NoFirefox Full support 1IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoEdge Mobile No support NoFirefox Android Full support 4Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs No support No
messageChrome Full support YesEdge Full support YesFirefox Full support 1IE Full support 6Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
nameChrome Full support YesEdge Full support YesFirefox Full support 1IE Full support 6Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
stack
Non-standard
Chrome Full support YesEdge Full support YesFirefox Full support 1IE Full support 10Opera Full support YesSafari Full support 6WebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support 6Samsung Internet Android Full support Yesnodejs Full support Yes
toSource
Non-standard
Chrome No support NoEdge No support NoFirefox Full support 1IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoEdge Mobile No support NoFirefox Android Full support 4Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs No support No
toStringChrome Full support YesEdge Full support YesFirefox Full support 1IE Full support 6Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes

Legend

Full support  
Full support
No support  
No support
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.

相关链接

文档标签和贡献者

标签: 
最后编辑者: zhangchen,