Error

Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. See below for standard built-in error types.

描述

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.

构造函数

Error()
创建新的 Error 对象。

静态方法

Error.captureStackTrace()
A non-standard V8 function that creates the stack property on an Error instance.

实例特性

Error.prototype.message
Error message.
Error.prototype.name
Error name.
Error.prototype.description
A non-standard Microsoft property for the error description. Similar to message .
Error.prototype.number
A non-standard Microsoft property for an error number.
Error.prototype.fileName
A non-standard Mozilla property for the path to the file that raised this error.
Error.prototype.lineNumber
A non-standard Mozilla property for the line number in the file that raised this error.
Error.prototype.columnNumber
A non-standard Mozilla property for the column number in the line that raised this error.
Error.prototype.stack
A non-standard Mozilla property for a stack trace.

实例方法

Error.prototype.toString()
Returns a string representing the specified object. Overrides the Object.prototype.toString() 方法。

范例

Throwing a generic error

Usually you create an Error object with the intention of raising it using the throw keyword. You can handle the error using the try...catch construct:

try {
  throw new Error('Whoops!')
} catch (e) {
  console.error(e.name + ': ' + e.message)
}
					

Handling a specific error

You can choose to handle only specific error types by testing the error type with the error's 构造函数 property or, if you're writing for modern JavaScript engines, instanceof keyword:

try {
  foo.bar()
} catch (e) {
  if (e instanceof EvalError) {
    console.error(e.name + ': ' + e.message)
  } else if (e instanceof RangeError) {
    console.error(e.name + ': ' + e.message)
  }
  // ... etc
}
					

Custom Error Types

You might want to define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to check the kind of error in the exception handler.  This results in cleaner and more consistent error handling code.

"What's a good way to extend Error in JavaScript?" on StackOverflow for an in-depth discussion.

ES6 Custom Error Class

Versions of Babel prior to 7 can handle CustomError class methods, but only when they are declared with Object.defineProperty() . Otherwise, old versions of Babel and other transpilers will not correctly handle the following code without additional configuration .

Some browsers include the CustomError constructor in the stack trace when using ES2015 classes.

class CustomError extends Error {
  constructor(foo = 'bar', ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params)
    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError)
    }
    this.name = 'CustomError'
    // Custom debugging information
    this.foo = foo
    this.date = new Date()
  }
}
try {
  throw new CustomError('baz', 'bazMessage')
} catch(e) {
  console.error(e.name)    //CustomError
  console.error(e.foo)     //baz
  console.error(e.message) //bazMessage
  console.error(e.stack)   //stacktrace
}
					

ES5 Custom Error Object

所有 browsers include the CustomError constructor in the stack trace when using a prototypal declaration.

function CustomError(foo, message, fileName, lineNumber) {
  var instance = new Error(message, fileName, lineNumber);
  instance.name = 'CustomError';
  instance.foo = foo;
  Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  if (Error.captureStackTrace) {
    Error.captureStackTrace(instance, CustomError);
  }
  return instance;
}
CustomError.prototype = Object.create(Error.prototype, {
  constructor: {
    value: Error,
    enumerable: false,
    writable: true,
    configurable: true
  }
});
if (Object.setPrototypeOf){
  Object.setPrototypeOf(CustomError, Error);
} else {
  CustomError.__proto__ = Error;
}
try {
  throw new CustomError('baz', 'bazMessage');
} catch(e){
  console.error(e.name); //CustomError
  console.error(e.foo); //baz
  console.error(e.message); //bazMessage
}
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'Error' in that specification.

浏览器兼容性

更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
Error Chrome 1 Edge 12 Firefox 1 IE 6 Opera 4 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs 0.1.100
Error() 构造函数 Chrome 1 Edge 12 Firefox 1 IE 6 Opera 4 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs 0.1.100
columnNumber
非标
Chrome No Edge No Firefox 1 IE No Opera No Safari No WebView Android No Chrome Android No Firefox Android 4 Opera Android No Safari iOS No Samsung Internet Android No nodejs No
fileName
非标
Chrome No Edge No Firefox 1 IE No Opera No Safari No WebView Android No Chrome Android No Firefox Android 4 Opera Android No Safari iOS No Samsung Internet Android No nodejs No
lineNumber
非标
Chrome No Edge No Firefox 1 IE No Opera No Safari No WebView Android No Chrome Android No Firefox Android 4 Opera Android No Safari iOS No Samsung Internet Android No nodejs No
message Chrome 1 Edge 12 Firefox 1 IE 6 Opera 5 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs 0.1.100
name Chrome 1 Edge 12 Firefox 1 IE 6 Opera 4 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs 0.1.100
stack
非标
Chrome 3 Edge 12 Firefox 1 IE 10 Opera 10.5 Safari 6 WebView Android ≤37 Chrome Android 18 Firefox Android 4 Opera Android 11 Safari iOS 6 Samsung Internet Android 1.0 nodejs 0.1.100
toSource
非标
Chrome No Edge No Firefox 1 — 74
1 — 74
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 Opera No Safari No WebView Android No Chrome Android No Firefox Android 4 Opera Android No Safari iOS No Samsung Internet Android No nodejs No
toString Chrome 1 Edge 12 Firefox 1 IE 6 Opera 4 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs 0.1.100

图例

完整支持
完整支持
不支持
不支持
非标。预期跨浏览器支持较差。
见实现注意事项。

另请参阅

Metadata