obs-portal/_middleware/error-handler.js

20 lines
686 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) {
case typeof err === 'string':
// custom application error
const is404 = err.toLowerCase().endsWith('not found');
const statusCode = is404 ? 404 : 400;
return res.status(statusCode).json({ message: err });
case err.name === 'ValidationError':
// mongoose validation error
return res.status(400).json({ message: err.message });
case err.name === 'UnauthorizedError':
// jwt authentication error
return res.status(401).json({ message: 'Unauthorized' });
default:
return res.status(500).json({ message: err.message });
}
}