How Node really works · Chapter 27 of 34

Error handling

By the end of this chapter you can tell an error to handle from a bug to crash on, and stop a Node server without losing an order. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The system
  • 5 tasks
  • Node.js
  • In the all labs plan

The first 2 chapters of How Node really works are free. This one comes with the all labs plan.

Why you need this

At 3:12 am the order server died with TypeError: Cannot read properties of undefined (reading 'price'), and nobody knew until Ravi opened the stall at 6. Earlier that week the UPI gateway timed out a few times and those errors were swallowed: customers paid, and the kitchen never saw the orders. And every deploy kills the server mid-order.

A try/catch everywhere does not fix this. It cannot see an error thrown later in a timer, it catches bugs you should not hide, and nothing in it helps when Docker stops the process. Node has separate tools for each.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    OrderError and isOperational: tell operational errors from bugs

    Finish the class OrderError(message, status), with status 400 when it is left out. It extends Error and keeps the message; its name is 'OrderError' (so its stack starts with OrderError too), it has the given status, and isOperational is true.

    Write isOperational(err). It returns true for anything whose isOperational is true, and for a system error whose code is in OPERATIONAL_CODES (a real missing file gives ENOENT). It returns false for everything else: a TypeError from a bug, a plain Error, an error with any other code such as ERR_INVALID_ARG_TYPE, and values that are not objects at all (null, undefined, a string such as 'ENOENT'). It never throws.

  2. Task 2

    readMenu: read the menu with an error-first callback, called once

    Write readMenu(file, callback). It reads the file as UTF-8 with the callback version of readFile from node:fs and parses it as JSON. It calls callback(null, menu) with the parsed menu, or callback(err) when the file cannot be read (the error from readFile, for example code ENOENT) or is not valid JSON (the SyntaxError).

    The callback runs exactly once, never twice, and never before readMenu has returned. If the caller's callback itself throws, that error is not caught and turned into a second call.

  3. Task 3

    loadMenus: load every branch menu even when some fail

    Write loadMenus(files). It reads every file as UTF-8 and parses it as JSON, and one bad file must not lose the others. It returns a promise of { menus, failed }: menus holds the menus that loaded, in the order of files; failed holds { file, code } for each file that did not, also in the order of files, where code is the error's code (ENOENT for a missing file) or, when the error has no code, its name (SyntaxError for a file that is not JSON).

    An empty list gives { menus: [], failed: [] }.

  4. Task 4 · interview question

    Interview: installCrashHandlers, log and exit on uncaught errors and unhandled rejections

    Write installCrashHandlers(log), with log console.error when it is left out. It adds two process handlers. On uncaughtException it logs crash: uncaughtException: <message>. On unhandledRejection it logs crash: unhandledRejection: <message>, where the reason may not be an Error: then it logs String(reason) instead (a rejected 'rider did not answer' logs crash: unhandledRejection: rider did not answer).

    After logging, both exit the process with code 1, even when an interval is still running. The log line goes through the log function you were given.

  5. Task 5

    gracefulShutdown: finish the orders in progress before stopping on SIGTERM

    Write gracefulShutdown(server, log), with log console.log when it is left out. When the process receives SIGTERM it logs shutting down, stops accepting new connections, and lets the requests in progress finish (a GET /slow that started before the signal still gets its 200 answer, chai ready). Once they are done it logs closed and exits with code 0.

    If closing takes more than 5 seconds, it exits with code 1 instead, and that safety timer must not itself keep the process alive.

What you will learn

  • Operational errors and bugs: error codes and your own error classes, so code can tell them apart.
  • Error-first callbacks and promises: calling back exactly once, and Promise.allSettled when some jobs fail.
  • The last line of defence: uncaughtException and unhandledRejection.
  • Graceful shutdown: SIGTERM and server.close.

More in The system

Build "Error handling" yourself

Tapri’s order server must never stall at the 4 pm rush. You learn why it would. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of How Node really works are free. This one comes with the all labs plan.