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.
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.
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.
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, wrapawaitcalls intry...catch; a rejected promise throws at theawait. - With
.then(), end the chain with.catch(); use.finally()for cleanup. - Always handle rejections: an unhandled one reports an
unhandledrejectionevent in browsers. fetch()rejects only for network failures. An HTTP 404 or 500 is a resolved response, so checkresponse.okyourself.
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.
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
Errorobjects. Throwing strings loses the stack trace; throwingnullmakescatch (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
undefinedor-1, not throw. finallyruns even afterreturnorthrow, and areturninsidefinallyoverrides the earlier result. Avoid returning fromfinally.- Parsing can fail:
JSON.parse()throwsSyntaxError,new URL()throwsTypeError, anddecodeURIComponent()can throwURIError. - Rejections need handlers. A promise created and forgotten that rejects is a bug.
- Use
AggregateError(fromPromise.any()) when several operations fail together, anderror.causeto 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.