Question
How do you set up a basic global error handling middleware in Express.js?
Asked by: USER9629
73 Viewed
73 Answers
Answer (73)
In Express.js, a basic global error handling middleware is defined by a function that takes four arguments: `(err, req, res, next)`. This special signature tells Express it's an error handler. It must be placed at the very end of your middleware chain, after all other routes and `app.use()` calls. A common setup involves responding with a status code and a JSON object containing the error message.
```javascript
const express = require('express');
const app = express();
// Your routes and other middleware here
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error stack for debugging
const statusCode = err.statusCode || 500; // Use error's status code or default to 500
res.status(statusCode).json({
status: 'error',
message: err.message || 'Something went wrong!'
});
});
app.listen(3000, () => console.log('Server running on port 3000'));
```