【发布时间】:2017-11-24 11:46:46
【问题描述】:
尝试创建自定义帮助方法以避免重复,我正在使用express-promise-router
app.js 创建了错误处理程序中间件
//errorHandler
app.use((err, req, res, next) => {
//const error = app.get('env') === 'development' ? err : {};
const error = err;
const code = err.code || '';
const status = err.status || 500;
res.status(status).json({
isresponse: 1,
res_time: Date(),
res_id: 'tempororyid',
res_data: {
error: {
code: code,
message: error.message
}
}
});
console.log(err);
});
errorHelper.js 用于所有错误帮助方法
module.exports = {
notFound: (req, res, next) => {
const err = new Error('url not found please check the documentation');
err.status = 404;
err.code = 'URLNotFound';
next(err);
},
emailExist: (req, res, next) => {
const err = new Error('the email is already associated with another user account');
err.code = 'EmailUsed';
err.status = 400;
next(err);
}
};
authController.js 用于身份验证
const User = require('../models/User');
const { emailExist } = require('../helpers/errorHelper');
module.exports = {
signup: async (req, res, next) => {
const userGuid = guid();
const email = req.body.email;
const existingUser = await User.findOne({email: email});
if(existingUser) {
emailExist();
}
const newUser = await User.create(req.body);
res.status(200).json({
isresponse: 1,
res_time: Date(),
res_id: 'TEMPID002',
res_data: {
success: 1,
data: []
}
});
}
}
得到以下错误
TypeError: next is not a function
at emailExist (D:\Workspace\path\path\path\errorHelper.js:13:4)
at signup (D:\Workspace\path\path\path\authController.js:26:4)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
POST /api/v1/signup 500 201.262 ms - 176
但是如果抛出如下错误,事情会按预期工作
if(existingUser) {
const error = new Error('the email is already associated with another user account');
error.code = 'CR_NU_EmailUsed';
error.status = 400;
next(error);
}
寻找急需的帮助
谢谢
【问题讨论】:
标签: javascript node.js express error-handling ecmascript-6