obs-portal/_middleware/error-handler.js

24 lines
697 B
JavaScript
Raw Normal View History

module.exports = errorHandler;
function errorHandler(err, req, res, next) {
2020-11-20 10:02:30 +00:00
switch (true) {
2020-11-20 10:06:32 +00:00
case typeof err === 'string': {
2020-11-20 10:02:30 +00:00
// custom application error
const is404 = err.toLowerCase().endsWith('not found');
const statusCode = is404 ? 404 : 400;
return res.status(statusCode).json({ message: err });
2020-11-20 10:06:32 +00:00
}
2020-11-20 10:02:30 +00:00
case err.name === 'ValidationError':
// mongoose validation error
return res.status(400).json({ message: err.message });
2020-11-20 10:06:32 +00:00
2020-11-20 10:02:30 +00:00
case err.name === 'UnauthorizedError':
// jwt authentication error
return res.status(401).json({ message: 'Unauthorized' });
2020-11-20 10:06:32 +00:00
2020-11-20 10:02:30 +00:00
default:
return res.status(500).json({ message: err.message });
}
}