Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Practical Pages

Error handling patterns

Concept page on JavaScript error handling patterns: try/catch/finally, custom errors, async errors with promises, guard clauses, and global handlers.

Things go wrong: input is invalid, a file is missing, a server is down. Good error handling decides where a failure should be noticed and who should deal with it. The rule of thumb is to catch an error only where you can do something useful about it (retry, show a message, use a fallback), and otherwise let it travel up to a place that can.

JavaScript signals errors by throwing a value. Throw Error objects (or subclasses), not strings, because only an Error carries a message, a name and a stack trace.

try, catch and finally

try runs code; if it throws, execution jumps to catch with the thrown value; finally runs afterwards in every case, even after return.

JS try / catch / finally

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Throwing and custom errors

Validate early and throw an error that says what is wrong. Subclassing Error lets callers tell your failures apart with instanceof, and the cause option chains the original error.

JS Custom errors and cause

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Rethrowing what you cannot handle

A catch block catches everything, including programming mistakes. Check the error type and rethrow what you do not understand.

JavaScript
try {
  save(form);
} catch (err) {
  if (err instanceof ValidationError) {
    showFieldError(err.field, err.message);
  } else {
    throw err; // not ours: let it bubble up
  }
}

Errors in asynchronous code

A try...catch only catches errors thrown while its block is running. It cannot catch an error thrown later inside a callback or a timer. For promises, errors become rejections:

  • With async/await, wrap await calls in try...catch; a rejected promise throws at the await.
  • With .then(), end the chain with .catch(); use .finally() for cleanup.
  • Always handle rejections: an unhandled one reports an unhandledrejection event in browsers.
  • fetch() rejects only for network failures. An HTTP 404 or 500 is a resolved response, so check response.ok yourself.
JS Async errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

(The last block throws inside a timer, so the error appears in the console, outside the try. That is the point of the demonstration.)

Guard clauses and defaults

Handle bad cases first and return early, so the main path stays flat. For values that may be missing, ?. and ?? avoid errors that you would otherwise have to catch.

JS Guards instead of exceptions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Global handlers

In browsers, window.addEventListener("error", ...) sees uncaught exceptions and window.addEventListener("unhandledrejection", ...) sees rejected promises nobody handled. Use them to log problems to a service, not as a replacement for local handling. In Node.js the equivalents are process.on("uncaughtException") and process.on("unhandledRejection").

Usage notes

  • Throw Error objects. Throwing strings loses the stack trace; throwing null makes catch (e) handling awkward.
  • Do not swallow errors. An empty catch {} hides bugs. At least log, or leave a comment explaining why ignoring is safe.
  • Do not use exceptions for ordinary control flow. Searching for a missing item should return undefined or -1, not throw.
  • finally runs even after return or throw, and a return inside finally overrides the earlier result. Avoid returning from finally.
  • Parsing can fail: JSON.parse() throws SyntaxError, new URL() throws TypeError, and decodeURIComponent() can throw URIError.
  • Rejections need handlers. A promise created and forgotten that rejects is a bug.
  • Use AggregateError (from Promise.any()) when several operations fail together, and error.cause to keep the original failure.
  • Wrap with context, not noise. Add what you were doing ("Could not load user"), keep the original as cause.

Browser support

try...catch, Error and promises are available everywhere. Optional catch binding, Error cause and AggregateError are supported in all current browsers; very old browsers may lack them.