Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 43 ยท Errors and Robustness

Error Handling

Handle errors in Express the right way: four-argument error middleware, a 404 handler, async errors in Express 5 vs 4, custom error classes and safe responses.

Things go wrong in every real server: a client sends bad JSON, a record does not exist, the database is down, a bug throws a TypeError. What matters is that each failure produces a sensible response, gets logged, and never takes the whole process down. Express gives you one central mechanism for this: error-handling middleware.

In this lesson you will learn how errors travel through an app, how to write the error handler and the 404 handler, how async errors differ between Express 4 and 5, and how custom error classes keep your controllers clean. Real Express code is read-only here; the runnable examples use the stand-in framework from Inside Express, which has the same four-argument convention.

How an error travels

Three ways to raise an error

throw A synchronous throw in a handler is caught for you.
next(err) Pass any error value to next to start error mode.
Rejected promise Express 5 turns it into next(err).

All three end up in the same place.

1 / 2

Once next(err) is called with an argument, Express skips every ordinary handler and goes to the next error-handling middleware. That is a function with exactly four parameters, (err, req, res, next). Express recognizes it by counting parameters, so you must declare all four even if you never use next.

flowchart LR
  A["Request"] --> B["Route handler"]
  B -->|"throws or next(err)"| C["Error middleware<br/>(err, req, res, next)"]
  B -->|"res.json(...)"| D["Response"]
  C --> D

A handler either responds itself or raises an error; the error middleware turns the error into a response.

The error handler

Register the error handler last, after all routes and other middleware, so every error can reach it.

JavaScript
app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.status ?? 500).json({
    error: err.status ? err.message : 'Internal Server Error',
  });
});

Express has a default error handler too. It responds with the status from err.status or err.statusCode (500 otherwise) and, outside production, includes the stack trace in an HTML page. That default is fine for learning but you normally replace it with JSON for APIs.

If you have already started sending a response when an error happens, you cannot send a second one. In a custom handler, check res.headersSent and delegate to the default handler with next(err); Express then closes the connection safely.

The 404 handler

A 404 is not an error in Express's eyes: no layer matched, so the request simply fell off the end of the list. You handle it with an ordinary middleware placed after all routes but before the error handler:

JavaScript
app.use((req, res) => {
  res.status(404).json({ error: `Cannot ${req.method} ${req.path}` });
});

Put it earlier and it would answer requests that later routes should handle. Put it after the error handler and it would never run for errors, which is fine, but the order "routes, 404, error handler" is the convention.

Custom error classes

Throwing plain Error objects forces every catcher to guess a status code. A small hierarchy of error classes lets any layer, including services that know nothing about HTTP, say what went wrong. The central handler then maps classes to responses.

JavaScript
export class AppError extends Error {
  constructor(message, status = 500, details) {
    super(message);
    this.name = this.constructor.name;
    this.status = status;
    this.details = details;
    this.expose = status < 500; // safe to show the message to clients?
  }
}

export class NotFoundError extends AppError {
  constructor(what = 'Resource') {
    super(`${what} not found`, 404);
  }
}

export class ValidationError extends AppError {
  constructor(errors) {
    super('Validation failed', 422, errors);
  }
}

In a class you can also call Error.captureStackTrace(this, this.constructor) at the end of the constructor. It rebuilds this.stack so the first frame is the code that created the error, not the error class's own constructor, which keeps logs short and readable.

Services throw new NotFoundError('Todo'), controllers do not need if (!todo) return res.status(404)..., and one handler decides how every error looks. This builds on Controllers and Services and Validating Input.

The expose flag encodes an important rule: for client errors (4xx) the message is meant for the client, but for server errors (5xx) the message may reveal internals such as table names, so you send a generic text and log the real one.

Runnable: errors, 404 and one central handler

Node.js Custom errors and a central handler

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the /crash line: the log shows the real message (connection to db-prod-3 refused), but the client only gets "Internal Server Error". /sync-throw shows that a plain SyntaxError with no status is treated as a 500 too, and the /nope request hits the 404 handler.

Async errors: Express 5 versus Express 4

How errors from async functions reach the error handler is the biggest practical difference between the versions.

Situation Express 4 Express 5
throw in a sync handler forwarded to the error handler forwarded
next(err) forwarded forwarded
throw in an async handler not forwarded: unhandled rejection, request hangs forwarded
rejected promise returned from middleware not forwarded forwarded

In Express 4 the safe patterns were try { ... } catch (e) { next(e); } in every handler, a wrapper like asyncHandler, or the express-async-errors package. In Express 5 you can just write the async function. One more case never forwards in either version: errors inside callbacks and timers that run after the handler returned, for example inside setTimeout or an event listener. There you must catch and call next(err) yourself, or the error becomes an uncaught exception.

JavaScript
app.get('/later', (req, res, next) => {
  setTimeout(() => {
    try {
      riskyWork();
      res.send('done');
    } catch (err) {
      next(err); // nobody else can catch this
    }
  }, 10);
});

Chaining error handlers

You may register several error handlers. Each one can handle the error or call next(err) to pass it on. A common split is a logging handler first and a responding handler second.

Node.js Two error handlers in a chain

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The broken JSON becomes a 400 (the parser attaches status = 400), the missing items causes a TypeError and therefore a 500, and in /partial the headers were already sent, so the handler can only end the response.

Error responses clients can use

Pick one error shape and keep it everywhere. A practical shape:

JSON
{
  "error": {
    "code": "VALIDATION_FAILED",
    "message": "Validation failed",
    "details": [{ "field": "name", "message": "is required" }]
  }
}

A stable machine-readable code lets front-end code branch on errors without parsing English sentences. Never include stack traces or raw database messages in production responses. Log them, ideally with a request id so you can find the matching log line; see Logging and Debugging.

Do not swallow errors. Calling res.status(500).json({}) inside every catch hides the cause. Let the error reach the central handler, which logs it once, properly.

Process-level errors

Express handlers cover errors inside requests. Errors outside that (an unhandled rejection in a background job, an exception in a timer) end up as unhandledRejection or uncaughtException events on process. After an uncaught exception the process state is unreliable, so the standard advice is to log it, finish in-flight work if possible, and exit so a process manager (see Deployment) can restart a fresh process.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does Express recognize an error-handling middleware?

    Express counts the declared parameters. Exactly four means it is an error handler, even if you never use next.
  2. 2. Where should the 404 handler go?

    A 404 means no route matched, so the handler must come after every route. The error handler stays last.
  3. 3. In Express 5, what happens when an async handler throws?

    Express 5 forwards rejected promises returned by handlers to the error handler. Express 4 did not.
  4. 4. Why send "Internal Server Error" instead of err.message for a 500?

    Server-side messages can expose internals. Log the detail, but give clients a generic message.
  5. 5. An error occurs after the response has started streaming. What should the handler do?

    Headers cannot be sent twice. Check res.headersSent and either call next(err) or end the response.

Summary

  • Errors arrive via throw, next(err) or (in Express 5) rejected promises, then skip to error middleware.
  • Error handlers have four parameters and are registered last; a 404 handler goes after the routes.
  • Custom error classes with a status and an expose flag let services describe failures without knowing HTTP.
  • Log the real error, send a safe message, and keep one consistent error shape.
  • Check res.headersSent, and catch errors yourself in timers and callbacks.

Next: Logging and Debugging.