I'm trying to set the error name err.name = 'ExpressValidatorError';
of an custom Error class class AppError extends Error
that is passed to centralErrorHandler to filter and handle errors by err.name.
I have did a lot of research but still couldn't figure out why err.name in centralErrorHandler console logs as undefined.
When I change return next(err); in auth.controller.js to throw err;, the err.name does console log as 'ExpressValidatorError' but i'm not sure if using throw is correct.
centralErrorHandler.js
module.exports = (err, req, res, next) => {
err.statusCode = err.statusCode || 500;
err.status = err.status || 'error';
let error = {...err};
console.log(error.name);
if(err.name === 'ExpressValidatorError') error = handleExpressValidatorError(err);
if(err.name === 'InternalOAuthError') error = handleInternalOAuthError(err);
res.status(error.statusCode).json({
status: error.status,
message: error.message
});
}
auth.controller.js
const {validationResult} = require('express-validator');
exports.signup = (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
let err = new AppError(`Invalid login credentials.`, 422);
err.name = 'ExpressValidatorError';
return next(err);
}
res.status(200).send(req.user);
}
appError.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);
}
}
module.exports = AppError;
"engines": { "node": "12.18.1", "npm": "6.14.5" }