Skip to content
tezvyn:
Menu

Centralized error-handling middleware

Source: interviewHardHow cards are made

Summary

Express error flow.

Key points

error middleware takes four args err, req, res, next, is defined last, and runs when next(err) is called or sync errors throw.

Watch out for

omitting the err parameter so Express treats it as normal middleware.

What's really being asked

This assesses understanding of Express's error pipeline and how to consolidate error responses instead of duplicating try/catch handling in every route.

The full answer

Error-handling middleware is distinguished solely by having four parameters: err, req, res, and next. Express inspects a middleware function's arity, and a four-argument function is treated as an error handler rather than a normal one. Errors reach it in two ways: when any handler calls next(err) with an argument, or when a synchronous route handler throws, which Express catches automatically. Note that for asynchronous errors in older Express you must pass them to next yourself, since Express 4 does not auto-catch rejected promises. You implement a centralized catch-all by defining one error handler after all your routes and other middleware. Inside it you log the error, optionally inspect a status property to choose a code, and send a single consistent response, for example a JSON error body with an appropriate status, avoiding leaking stack traces to clients in production.

The mistakes people make

Defining the handler with three parameters, so Express never invokes it for errors. Placing it before the routes, so errors thrown later never reach it. Assuming async rejections are caught automatically in Express 4 without next(err). Sending raw stack traces to the client.

What usually comes next

How do you forward async errors to the handler. How does Express 5 change async error handling. How would you attach a status code to a custom error.

A concrete example

After all routes you add app.use((err, req, res, next) => { console.error(err); res.status(err.status || 500).json({ error: err.message }); });. A route doing next(new Error('boom')) or throwing synchronously lands here, producing a uniform 500 JSON response and one place to log every failure.

Interview question

What distinguishes an Express error-handling middleware from a regular one?

  • a.It has four parameters (err, req, res, next), and Express detects this signatureCorrect
  • b.It must be named errorHandler
  • c.It is registered with app.error instead of app.use
  • d.It returns a Promise rejection instead of calling next
Why?

Express identifies error handlers by their four-argument arity and routes errors to them. The name is irrelevant, there is no app.error method, and it is still registered with app.use.

Just read this? Test yourself on what you have been reading.

Read the original → expressjs.com

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on express — each one lists the topics its interview covers.

See open roles