xxxxxxxxxx
const express = require('express');
const app = express();
app.use(express.json());
// Example route
app.get('/', (req, res) => {
throw new Error('Something went wrong!');
});
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: err.message });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
xxxxxxxxxx
//app.js
//we need to put this code at last,this code run when there is no route match
app.all('*',(req,res,next)=> {
const err= new Error(`Can't find ${req.originalUrl} on this server!`)
err.status=404
err.statusCode=404
next(err)
})
//when we use next(err) it will go to error handling middleware and it will catch error and send response.
app.use((err,req,res,next)=> {
err.statusCode= err.statusCode || 500
err.status= err.status || 'error'
res.status(err.statusCode).json({
status:err.status,
message:err.message
})
})
xxxxxxxxxx
function errorHandler (err, req, res, next) {
if (res.headersSent) {
return next(err)
}
res.status(500)
res.render('error', { error: err })
}
xxxxxxxxxx
app.use((err, req, res, next) => {
res.status(500).json({ message: err.message });
});