节点 - 自定义错误帮助程序

时间:2017-11-24 11:46:46

标签: javascript node.js express error-handling ecmascript-6

尝试创建自定义帮助方法以避免重复,并且我使用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);
}

寻找急需的帮助

谢谢

0 个答案:

没有答案