Is there a way to add middleware or app.use() to catch all possible errors?
I have tried some global try-catch approaches but it looks so fragile.
CodePudding user response:
You can handle your errors like this:
res.status(500).send({ msg: 'Wrong email' })
And you can change the status code to send different type of errors or responses:
res.status(404).send({ msg: 'Not found' })
res.status(200).send({ msg: 'successful' })
CodePudding user response:
My approach would be like below
Place below code in
server.js or index.js
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
app.all('*', (req, res, next) => {
next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});
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
});
});
app.use((req, res, next) => {
console.log("Middleware 1 called.")
console.log(req.path)
next() // calling next middleware function or handler
})
app.get('/', (req, res) => {
console.log("Route handler called.")
res.send("Hello world!") // response sent back – no more middleware called
})