Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Error

BaselineWidely available *

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

Description

Runtime errors result in newError objects being created and thrown.

Error is aserializable object, so it can be cloned withstructuredClone() or copied betweenWorkers usingpostMessage().

Error types

Besides the genericError constructor, there are other core error constructors in JavaScript. For client-side exceptions, seeException handling statements.

EvalError

Creates an instance representing an error that occurs regarding the global functioneval().

RangeError

Creates an instance representing an error that occurs when a numeric variable or parameter is outside 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 whenencodeURI() ordecodeURI() are passed invalid parameters.

AggregateError

Creates an instance representing several errors wrapped in a single error when multiple errors need to be reported by an operation, for example byPromise.any().

InternalErrorNon-standard

Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".

Constructor

Error()

Creates a newError object.

Static properties

Static methods

Error.captureStackTrace()

A non-standard function that creates thestack property on the provided object.

Error.isError()

Returnstrue if the argument is an error, orfalse otherwise.

Error.prepareStackTrace()Non-standardOptional

A non-standard function that, if provided by user code, is called by the JavaScript engine for thrown exceptions, allowing the user to provide custom formatting for stack traces. See theV8 Stack Trace API docs.

Instance properties

These properties are defined onError.prototype and shared by allError instances.

Error.prototype.constructor

The constructor function that created the instance object. ForError instances, the initial value is theError constructor.

Error.prototype.name

Represents the name for the type of error. ForError.prototype.name, the initial value is"Error". Subclasses likeTypeError andSyntaxError provide their ownname properties.

Error.prototype.stackNon-standard

A non-standard property for a stack trace.

These properties are own properties of eachError instance.

cause

Error cause indicating the reason why the current error is thrown — usually another caught error. For user-createdError objects, this is the value provided as thecause property of the constructor's second argument.

columnNumberNon-standard

A non-standard Mozilla property for the column number in the line that raised this error.

fileNameNon-standard

A non-standard Mozilla property for the path to the file that raised this error.

lineNumberNon-standard

A non-standard Mozilla property for the line number in the file that raised this error.

message

Error message. For user-createdError objects, this is the string provided as the constructor's first argument.

Instance methods

Error.prototype.toString()

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

Examples

Throwing a generic error

Usually you create anError object with the intention of raising it using thethrow keyword.You can handle the error using thetry...catch construct:

js
try {  throw new Error("Whoops!");} catch (e) {  console.error(`${e.name}: ${e.message}`);}

Handling a specific error type

You can choose to handle only specific error types by testing the error type with theinstanceof keyword:

js
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.  else {    // If none of our cases matched leave the Error unhandled    throw e;  }}

Differentiate between similar errors

Sometimes a block of code can fail for reasons that require different handling, but which throw very similar errors (i.e., with the same type and message).

If you don't have control over the original errors that are thrown, one option is to catch them and throw newError objects that have more specific messages.The original error should be passed to the newError in the constructor'soptions parameter as itscause property. This ensures that the original error and stack trace are available to higher-level try/catch blocks.

The example below shows this for two methods that would otherwise fail with similar errors (doFailSomeWay() anddoFailAnotherWay()):

js
function doWork() {  try {    doFailSomeWay();  } catch (err) {    throw new Error("Failed in some way", { cause: err });  }  try {    doFailAnotherWay();  } catch (err) {    throw new Error("Failed in another way", { cause: err });  }}try {  doWork();} catch (err) {  switch (err.message) {    case "Failed in some way":      handleFailSomeWay(err.cause);      break;    case "Failed in another way":      handleFailAnotherWay(err.cause);      break;  }}

Note:If you are making a library, you should prefer to use error cause to discriminate between different errors emitted — rather than asking your consumers to parse the error message. See theerror cause page for an example.

Custom error types can also use thecause property, provided the subclasses' constructor passes theoptions parameter when callingsuper(). TheError() base class constructor will readoptions.cause and define thecause property on the new error instance.

js
class MyError extends Error {  constructor(message, options) {    // Need to pass `options` as the second parameter to install the "cause" property.    super(message, options);  }}console.log(new MyError("test", { cause: new Error("cause") }).cause);// Error: cause

Custom error types

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

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

Warning:Builtin subclassing cannot be reliably transpiled to pre-ES6 code, because there's no way to construct the base class with a particularnew.target withoutReflect.construct(). You needadditional configuration or manually callObject.setPrototypeOf(this, CustomError.prototype) at the end of the constructor; otherwise, the constructed instance will not be aCustomError instance. Seethe TypeScript FAQ for more information.

Note:Some browsers include theCustomError constructor in the stack trace when using ES2015 classes.

js
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 (non-standard)    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); // stack trace}

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-error-objects

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp