JavaScript Error()
The Error() constructor creates Error objects.
Error objects represent runtime errors.
Error is the base constructor for all built-in JavaScript error types.
Around the Error Object there is often confusion about:
- Error vs plain objects
- Error vs error types (TypeError, RangeError, ...)
- Throwing values vs throwing Error objects
- Inheritance
Syntax
Error()
Error(message)
Error(message, options)
new Error()
new Error(message)
new Error(message, options)
Parameters
| Parameter | Description |
|---|---|
| message | Optional. A description of the error. |
| options | Optional. Additional options such as cause. |
Return Value
| Call | Returns |
|---|---|
Error(...) |
An Error object |
new Error(...) |
An Error object |
Creating an Error
Example
const err = new Error("Something went wrong");
Common Properties
| Property | Description |
|---|---|
name |
The error type name. |
message |
The error message. |
cause |
An optional underlying cause. |
Example
const err = new Error("Something went wrong");
let text = err.name + ": " + err.message;
Throwing Errors
Error objects are commonly used with the throw statement.
Example
throw new Error("Invalid value");
Object Hierarchy
Error objects inherit from Object.
The Error constructor is the base constructor for built-in error types.
Object └─ Error ├─ AggregateError ├─ EvalError ├─ RangeError ├─ ReferenceError ├─ SyntaxError ├─ TypeError └─ URIError
| Error Type | Description |
|---|---|
| Error | Generic error |
| AggregateError | Multiple errors |
| RangeError | Value outside allowed range |
| ReferenceError | Invalid variable reference |
| SyntaxError | Invalid syntax |
| TypeError | Invalid value type |
| URIError | URI encoding or decoding error |
Error Objects Are Not Plain Objects
Error objects are created by the Error constructor.
They are not the same as ordinary object literals.
Example
const err = new Error("Wrong value");
(err instanceof Error) // true
Custom Error Types
You can create your own error types by extending Error.
Example
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
Type Information
| Property | Value |
|---|---|
| Constructor Type | Function |
| Creates | Error objects |
| Inherits From | Object |
| Base Constructor For | AggregateError, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError |
Browser Support
new Error() is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |