Introduction
Error handling helps your app stay strong and friendly when things go wrong. It stops crashes and shows helpful messages instead of confusing errors.
Error handling helps your app stay strong and friendly when things go wrong. It stops crashes and shows helpful messages instead of confusing errors.
app.use((err, req, res, next) => {
res.status(500).send('Something broke!')
})app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Internal Server Error')
})app.get('/user/:id', (req, res, next) => { const user = getUser(req.params.id) if (!user) { const err = new Error('User not found') err.status = 404 return next(err) } res.send(user) })
This simple Express app throws an error on the home page route. The error handler catches it, logs the message, and sends a friendly response.
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('Something went wrong!') }) app.listen(3000, () => console.log('Server running on http://localhost:3000'))
Always place error-handling middleware after all other app routes and middleware.
Use error handling to keep your app from crashing and to give users clear feedback.
Error handling keeps your app stable and user-friendly.
It catches problems early and prevents crashes.
Express uses special middleware with four parameters for error handling.
app.get('/data', (req, res, next) => {
try {
throw new Error('Failed to load');
} catch (err) {
next(err);
}
});
app.use((err, req, res, next) => {
res.status(500).send('Error: ' + err.message);
});/data?app.use((err, req, res) => {
res.status(500).send('Oops!');
});app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong, please try again later.');
});Pass the test and this pattern moves unknown