err.name
在 centralErrorHandler console logs 显示 undefined
.
该怎么设置才能在 centralErrorHandler 获得 error name err.name = 'ExpressValidatorError';
如果把 return next(err);
in auth.controller.js 改成 throw err;
, err.name
就能成功获得 'ExpressValidatorError'
但不确定 throw err;
这样做对不对。
centralErrorHandler.js
module.exports = (err, req, res, next) => {
console.log(err.name);
if(err.name === 'ExpressValidatorError') err = handleExpressValidatorError(err);
}
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;
在
exports.signup = (req, res)
里加next
解决了undefined
的问题。