Skip to content

Instantly share code, notes, and snippets.

@ManotLuijiu
Created June 17, 2021 06:28
Show Gist options
  • Save ManotLuijiu/ab3f38805983813922a078428c475d7f to your computer and use it in GitHub Desktop.
Save ManotLuijiu/ab3f38805983813922a078428c475d7f to your computer and use it in GitHub Desktop.
Error handler for NodeJS Project
const ErrorResponse = require('./errorResponse');
const logger = require('./logger');
const colors = require('colors');
colors.enable();
const errorHandler = (err, req, res, next) => {
let error = { ...err };
error.message = err.message;
// logger.error(err.stack.red);
console.log(err.stack.red);
// Mongoose bad ObjectId
if (err.name === 'CastError') {
const message = `Source not found with id of ${err.value}`;
const reason = `reason${err.reason}`;
const alignReason = reason.split(':')[1].trim();
console.log(alignReason);
error = new ErrorResponse(message, 404, alignReason);
}
res.status(error.statusCode || 500).json({
name: error.name,
success: false,
error: error.message || 'Server Error',
reason: error.reason,
});
};
module.exports = errorHandler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment