Typorithm · medium

Errors & Diagnostics

node-error-handlingnodejserror-handlingcustom-errorprocess
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Errors & Diagnostics

0%

Testing & Debug

Wrap await in try/catch to handle rejected promises. process.on("unhandledRejection") and ("uncaughtException") are last-resort hooks to log then exit. Subclass Error with a code for structured failures, and debug with node --inspect plus Chrome DevTools or the VS Code debugger.

The everyday pattern is try/catch around an await — a rejected promise becomes a catchable error you can log, retry, or rethrow.

process.on("unhandledRejection") and process.on("uncaughtException") are last-resort safety nets: the process is in an unknown state, so log the error and then process.exit(1) rather than continuing.

Custom Error subclasses that carry a code give structured, matchable failures, and node --inspect lets you attach Chrome DevTools or the VS Code debugger for breakpoints and stepping.

01

try/catch around await turns rejections into catchable errors.

02

unhandledRejection / uncaughtException: log then exit.

03

Custom Error subclass with a code; debug via node --inspect.

class HttpError extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
  }
}

try {
  await risky();
} catch (err) {
  console.error(err);
}

process.on("unhandledRejection", (err) => {
  console.error(err);
  process.exit(1);
});

Read the implementation

Connect each part of the code to the concept before you type.

1. Custom Error subclass

Subclassing Error lets you attach a code and carry structured failure info.

class HttpError extends Error {

2. Pass the message

Calling super(message) sets the standard Error message before you add custom fields.

super(message);

3. try/catch around await

Wrapping await in try/catch turns a rejected promise into a catchable error.

try {
  await risky();
} catch (err) {

4. Last-resort handler

unhandledRejection catches promises that escaped every catch — log it as a last resort.

process.on("unhandledRejection", (err) => {

5. Exit after logging

After an uncaught failure the process is in an unknown state, so log and then exit.

process.exit(1);

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Errors & Diagnostics: Lesson & Practice · Typorithm | ApplyDjinn