An Error object describes a problem that happened while your program was running. You create one with new Error("message") and report it with throw. JavaScript also creates error objects by itself, for example when your code reads a property of null.
When an error is thrown, the normal flow stops and JavaScript looks for the nearest try...catch block. If it finds one, your catch code handles the problem and the program can go on. If it finds none, the program stops and the error is printed in the console.
err.name tells you the kind of problem, such as TypeError. err.message explains it in words. err.stack adds the list of functions that were running.
Syntax
JavaScript Syntax
Create an error, read its parts, then throw and catch it:
JavaScript
const err = new Error("Something went wrong"); // create an error object
console.log(err.name); // "Error"
console.log(err.message); // "Something went wrong"
try {
throw err; // report the problem
} catch (e) {
console.log(e.message); // handle it here
} finally {
console.log("done"); // always runs
}
const wrapped = new Error("Save failed", { cause: err }); // keep the original error
Reference
Core Ideas
Ideas every Error tutorial in this series builds on:
Idea
Example
Remember
new Error()
new Error("Disk full")
Creates an error; the message is optional
name
err.name
The kind of error, such as "TypeError"
message
err.message
A readable explanation of the problem
stack
err.stack
Text listing the functions that were running
cause
new Error("Failed", { cause: err })
Keeps the original error inside a new one
throw
throw new Error("Oops")
Stops the current code and jumps to the nearest catch
try...catch
try { ... } catch (err) { ... }
Handles a thrown error so the program can continue
finally
finally { cleanup(); }
Runs whether or not an error happened
instanceof
err instanceof TypeError
Tells you which kind of error you caught
Compare
Built-in Error Types
JavaScript creates these error types by itself. You can create them too with new:
Type
JavaScript throws it when...
Example
Error
You or a library create a general error
new Error("Oops")
TypeError
A value is not the type an operation needs
null.length
ReferenceError
You use a variable that does not exist
missingVariable
RangeError
A number is outside the allowed range
new Array(-1)
SyntaxError
Code or text cannot be parsed
JSON.parse("{bad")
URIError
A URI function receives bad input
decodeURIComponent("%")
AggregateError
Several errors are wrapped into one, for example by Promise.any()
new AggregateError([e1, e2])
All of these types extend Error, so err instanceof Error is true for each of them. When you handle errors, check the specific type first (err instanceof TypeError) and fall back to the general Error. An older type called EvalError still exists, but modern JavaScript does not throw it.
Behavior
How Errors Work
Throw stops the current code
The moment throw runs, the rest of that function is skipped. JavaScript walks back through the functions that called it until it finds a catch.
Errors travel up the call stack
You do not have to catch an error where it happens. A function can let it move up to a caller that knows what to do. Example 3 shows the path.
finally always runs
Use finally for cleanup, such as closing a file or hiding a loading spinner. It runs after a normal finish, after a caught error, and even when the error is not caught here.
You can throw any value
JavaScript accepts throw "oops" and throw 404, but then you lose the message and the stack. Always throw Error objects, and use Error.isError() in a catch block when you are not sure what you received.
Add context with cause
When you catch a low-level error and throw a friendlier one, pass the original as { cause: err }. The reader of the log can then see both. Example 2 shows it.
Practice
Real-Life Uses
Errors are how code says "I cannot continue, and here is why". Typical places you will meet them:
Use
What the error does
Form validation
Throw a ValidationError with a clear message when a field is empty or invalid.
Failed network calls
Create an Error when fetch() answers with a bad status, so the caller can show a retry button.
Reading JSON
JSON.parse() throws a SyntaxError for broken text. Catch it and fall back to default settings.
Logging and debugging
Show err.message to the user and keep err.stack in the log so developers can find the line that failed.
Custom error classes
Classes such as PaymentError let your code handle different problems in different ways.
Code
JavaScript Examples
Three short programs that show errors at work. Each one only prints plain text, so the output is the same in Node.js and in the browser console.
Example 1 — Meet the Built-in Error Types
Each test breaks a rule on purpose. The catch block prints the type of error JavaScript created.
Wrap each test. Every test is a small function. Calling it inside try lets the loop continue after an error instead of stopping the program.
JavaScript picks the type. Reading a property of null is a TypeError, an unknown variable is a ReferenceError, and so on. err.name shows which one it was.
One family. The last part of each line shows that every type is also an Error, so instanceof Error is always true.
Example 2 — Create a Custom Error with a Cause
A payment function turns a low-level RangeError into a friendlier PaymentError and keeps the original inside cause.
An Error is an object that describes a problem in your program. It has a name (the kind of error), a message (the explanation) and usually a stack (the functions that were running). You create one with new Error("message") and report it with throw.
Write throw new Error("message") where the problem happens. Put the risky code inside try { ... } and handle the problem in catch (err) { ... }. Use finally { ... } for cleanup code that must always run.
Error is the general type. TypeError, RangeError, ReferenceError, SyntaxError and URIError are more specific types that JavaScript throws for particular problems, such as the wrong kind of value or a number out of range. All of them extend Error.
JavaScript allows it, but it is a bad habit: a string has no stack and no name, so debugging is harder. Always throw Error objects. When you catch values from code you do not control, check them with Error.isError() before you read message.
The finally block runs after try and catch no matter what happened: when the code finished normally, when an error was caught, and even when the error was not caught in this function. It is the right place for cleanup.