← Back to JavaScript, page 2

javascript-0034 · Medium mid

How does error handling work in JavaScript? Cover try/catch/finally, custom errors, error.cause, and async errors.

try/catch/finally handles thrown values synchronously, and a finally block always runs. Custom errors extend Error so they carry a name, a message, a stack, and extra fields, and error.cause chains the original failure. In async code, a rejected promise must be caught with .catch or try/catch around await; an outer try/catch does not catch an un-awaited promise.

Full answer

Any value can be thrown, but throwing Error objects is the standard because they carry a message, a name, and a stack. A try block runs code. If something throws, control jumps to catch. The finally block runs in every case, including after a return, and it is the right place to release resources. A return inside finally overrides earlier returns and swallows errors, so it is best avoided.

Custom error classes extend Error so code can tell failure types apart with instanceof and so they can carry fields such as an HTTP status code. Call super(message) and set this.name. The cause option, new Error('message', { cause: original }), links the lower-level error that triggered this one, so wrapping an error keeps the full story.

Catch only what the code can handle. After checking the type, re-throw unknown errors, because hiding them makes bugs hard to find.

Async code adds a rule: a rejection is not a thrown exception in the current call stack. await converts a rejection into a throw at that line, so try/catch works around await. A promise that is not awaited or returned escapes the surrounding try/catch, and if nobody handles it, the runtime reports an unhandled rejection (Node.js exits with an error by default, and browsers fire an unhandledrejection event).

Global handlers (window.onerror, unhandledrejection, process.on('uncaughtException')) are for logging, not for continuing normally.

javascript
class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}

function parseMarks(text) {
  try {
    const marks = JSON.parse(text);
    if (marks < 0 || marks > 100) throw new ValidationError('Marks out of range', 'marks');
    return marks;
  } catch (error) {
    if (error instanceof ValidationError) throw error;
    throw new Error('Could not read marks', { cause: error });
  } finally {
    console.log('parse attempted for', JSON.stringify(text));
  }
}

for (const input of ['85', '150', 'abc']) {
  try {
    console.log('result:', parseMarks(input));
  } catch (error) {
    console.log(error.name, '-', error.message, error.field ?? '', error.cause?.name ?? '');
  }
}

function returnsFromTry() {
  try {
    return 'from try';
  } finally {
    console.log('finally runs before the return completes');
  }
}
console.log(returnsFromTry());

const failLater = () => new Promise((_, reject) => setTimeout(() => reject(new Error('async failure')), 10));

(async () => {
  try {
    failLater(); // not awaited: the catch below cannot see it
    console.log('try block finished normally');
  } catch (error) {
    console.log('never printed');
  }
  try {
    await new Promise((resolve) => setTimeout(resolve, 30));
    await failLater();
  } catch (error) {
    console.log('caught with await:', error.message);
  }
})();
process.on('unhandledRejection', (reason) => console.log('unhandled rejection:', reason.message));

Run with Node.js v24.22.1 as js-34.js; two runs gave identical output. Output: parse attempted for "85" result: 85 parse attempted for "150" ValidationError - Marks out of range marks parse attempted for "abc" Error - Could not read marks SyntaxError finally runs before the return completes from try try block finished normally unhandled rejection: async failure caught with await: async failure

Key points

  • Throw Error objects; they carry message, name, and stack.
  • finally always runs; avoid return inside it.
  • Custom errors extend Error and support instanceof checks; use cause to chain errors.
  • Catch what you can handle and re-throw the rest.
  • An un-awaited rejected promise escapes try/catch and becomes an unhandled rejection.

Common mistakes

  • Swallowing errors with an empty catch block.
  • Throwing strings instead of Error objects, so there is no stack trace.
  • Forgetting to await or return a promise inside try, so the catch never runs.
  • Wrapping an error without cause and losing the original stack.

Follow-ups

  • What is the difference between throw in a callback and a rejection in a promise?
  • How does error handling differ between Promise.all and Promise.allSettled?
  • How would you report errors from a React or Vue component tree?

Tips

  • Show one custom error with a field, and one wrap with cause; it proves you use modern features.
  • State the re-throw rule: handle what you understand, re-throw the rest.
  • Explain why an un-awaited promise escapes the try; interviewers like this trap.