Javascript 节点-自定义错误帮助程序
试图创建自定义帮助器方法以避免重复,我正在使用Javascript 节点-自定义错误帮助程序,javascript,node.js,express,error-handling,ecmascript-6,Javascript,Node.js,Express,Error Handling,Ecmascript 6,试图创建自定义帮助器方法以避免重复,我正在使用expresspromise路由器 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
expresspromise路由器
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
寻找急需的帮助
谢谢
module.exports={
未找到:()=>{
const err=新错误(“未找到url,请检查文档”);
err.status=404;
err.code='URLNotFound';
返回错误;
},
emailExist:()=>{
const err=new Error('电子邮件已与另一个用户帐户关联');
err.code='EmailUsed';
err.status=400;
返回错误;
},
响应:(res,res_数据)=>{
res.status(200).json({
以色列答复:1,
恢复时间:日期(),
res_id:'TEMPID002',
RESU数据
});
}
};谢谢你的回复,我真的很感激,你的回答真的帮助了我。非常感谢您,您真是太棒了。不过我有一个快速的问题,我如何防止重复我发送的响应,例如res.status(200).json({isresponse:1,res_time:Date(),res_id:'TEMPID002',resu data:{success:1,data:newUser})
我只想修改res\u数据
部分,你是说对所有应用程序进行全局设置还是只对请求进行全局设置?对全局设置,对于服务器的每个响应,isresponse
,res\u时间
,res\u id
,res\u数据
保持不变,唯一改变的是resu数据的内容
它可能包含数据或错误,resu数据:{success:1,data:[]}
如果错误resu数据:{error:{code:'',消息:'}}
,我编辑我的答案。我在errors helper中添加了一个响应函数,您可以将它放在任何您想要的地方,但这就是概念
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);
}