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 实例

Runtime errors result in new Error objects being created and thrown.

Error types

Besides the generic Error constructor, there are seven other core error constructors in JavaScript. For client-side exceptions, see Exception handling statements.

EvalError
Creates an instance representing an error that occurs regarding the global function eval().
InternalError 
Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
RangeError
Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
ReferenceError
Creates an instance representing an error that occurs when de-referencing an invalid reference.
SyntaxError
Creates an instance representing a syntax error.
TypeError
Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
URIError
Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.

属性

方法

例子

抛出一个基本错误

通常你会使用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 (ECMA-262)
Error
Living Standard

浏览器兼容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
ErrorChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 6Opera Full support 4Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support 0.1.100
Error() constructorChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 6Opera Full support 4Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support 0.1.100
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 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 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 NoFirefox Android Full support 4Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs No support No
messageChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 6Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support 0.1.100
nameChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 6Opera Full support 4Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support 0.1.100
stack
Non-standard
Chrome Full support 3Edge Full support 12Firefox Full support 1IE Full support 10Opera Full support 10.5Safari Full support 6WebView Android Full support ≤37Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 11Safari iOS Full support 6Samsung Internet Android Full support 1.0nodejs Full support 0.1.100
toSource
Non-standard
Chrome No support NoEdge No support NoFirefox No support 1 — 74
Notes
No support 1 — 74
Notes
Notes Starting in Firefox 74, toSource() is no longer available for use by web content. It is still allowed for internal and privileged code.
IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android 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 1Edge Full support 12Firefox Full support 1IE Full support 6Opera Full support 4Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support 0.1.100

Legend

Full support  
Full support
No support  
No support
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
See implementation notes.
See implementation notes.

相关链接