Express
Express error middleware
An Express error handler is middleware that receives an error and can translate it into a safe HTTP response. Express 5 forwards thrown errors and rejected promises returned by route handlers to error middleware. Detached asynchronous work still needs explicit ownership. Register a not-found handler after normal routes, then an error handler with four parameters. If headers are already sent, delegate instead of trying to rewrite the response. Never send arbitrary internal exception messages to clients. Static example only; runtime NOT RUN. Source: https://expressjs.com/en/guide/error-handling/.
Formal Syntax & Structure
nodejs syntaxnodejs
app.use((err, req, res, next) => { /* handle */ })Working Example
Example Snippetnodejs
import express from 'express';const app = express();app.get('/catalog', async () => { throw new Error('Storage unavailable'); });app.use((req, res) => res.status(404).json({ code: 'NOT_FOUND' }));app.use((err, req, res, next) => { if (res.headersSent) return next(err); res.status(500).json({ code: 'INTERNAL_ERROR' });});export default app;