【问题标题】:Node - Custom error helpers节点 - 自定义错误助手
【发布时间】: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


    【解决方案1】:

    module.exports = {
        notFound: () => {
            const err = new Error('url not found please check the documentation');
                err.status = 404;
                err.code = 'URLNotFound';
                return err;
        },
    
        emailExist: () => {
            const err = new Error('the email is already associated with another user account');
                err.code = 'EmailUsed';
                err.status = 400;
                return err;
        },
        
        response:(res ,res_data) => {
        
             res.status(200).json({
                isresponse: 1,
                res_time: Date(),
                res_id: 'TEMPID002',
                res_data
            });
            
        }
    };

    const User = require('../models/User');
    const { emailExist ,response} = 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) {
               return next(emailExist()); 
            }
    
            const newUser = await User.create(req.body);
            const res_data =  {
                    success: 1,
                    data: []
            }
            return response(res,res_data)
          
        }
    }

    【讨论】:

    • 谢谢你的回复我真的很感激,你的回答真的帮助了我。非常感谢你,你太棒了。
    • 我有一个快速的问题,我如何防止重复我发送的回复,例如res.status(200).json({ isresponse: 1, res_time: Date(), res_id: 'TEMPID002', res_data: { success: 1, data: newUser } }); 我只想修改res_data 部分
    • 您的意思是使其对所有应用程序全局化还是仅对请求全局化?
    • 是的全局,对于来自服务器的每个响应,isresponseres_timeres_idres_data 保持不变,唯一变化的是 res_data 的内容它可能包含数据或错误,res_data: {success: 1, data: []} 如果错误 res_data: {error:{code: '', message: ''} }
    • 我编辑我的答案。我在错误助手中添加了一个响应函数,你可以把它放在你想要的任何地方,但这是概念
    猜你喜欢
    • 2012-08-08
    • 1970-01-01
    • 2017-01-11
    • 2014-02-08
    • 2012-10-15
    • 2016-08-25
    • 1970-01-01
    • 2018-11-21
    • 2011-02-07
    相关资源
    最近更新 更多