Created
June 17, 2021 06:28
-
-
Save ManotLuijiu/ab3f38805983813922a078428c475d7f to your computer and use it in GitHub Desktop.
Error handler for NodeJS Project
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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