0
0
Expressframework~5 mins

Error-handling middleware signature in Express

Choose your learning style9 modes available
Introduction

Error-handling middleware helps catch and respond to errors in your app. It keeps your app from crashing and shows helpful messages.

When you want to catch errors from routes or other middleware
When you want to send a friendly error message to users
When you want to log errors for debugging
When you want to handle different error types differently
When you want to keep your app running smoothly even if something goes wrong
Syntax
Express
function errorHandler(err, req, res, next) {
  // handle the error
}

Error-handling middleware always has four parameters: err, req, res, and next.

Express knows it is error-handling middleware because of the four parameters.

Examples
Basic error handler that sends a 500 status and a simple message.
Express
app.use(function (err, req, res, next) {
  res.status(500).send('Something broke!')
})
Logs the error stack to the console and sends a JSON response with the error message.
Express
app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).json({ error: err.message })
})
Sample Program

This app throws an error on the home route. The error-handling middleware catches it, logs the message, and sends a 500 response.

Express
import express from 'express'
const app = express()

app.get('/', (req, res) => {
  throw new Error('Oops!')
})

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

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000')
})
OutputSuccess
Important Notes

Always place error-handling middleware after all other middleware and routes.

Calling next() inside error middleware passes the error to the next error handler.

Summary

Error-handling middleware has four parameters: err, req, res, next.

It catches errors and prevents app crashes.

Use it to send user-friendly error messages and log problems.