[英]Node.js error handling setup not working as intended
I am trying to have all my error messages in one file, each error is denoted by an error code, then in my functions/services, when there is an error, I call a function that takes the error code as an argument, then returns an object to the client with the error code and the respective error message from the errors.js file. 我试图将所有错误消息保存在一个文件中,每个错误都用一个错误代码表示,然后在我的函数/服务中,当出现错误时,我调用一个以错误代码为参数的函数,然后返回带有错误代码和来自errors.js文件的相应错误消息的客户端对象。 as an example, a user trying to register with an email that already exists in the database, here is how I try to do it:
例如,一个用户尝试使用数据库中已经存在的电子邮件进行注册,这是我尝试执行的操作:
// userService.js -- where my register function is const { errorThrower } = require('../../utils/errorHandlers'); ... static async registerNewUser(body) { const exists = await User.where({ email: body.email }).fetch(); if(exists) { errorThrower('400_2'); } ... }
errorHandlers.js file: errorHandlers.js文件:
exports.errorThrower = (errCode) => { throw Object.assign(new Error(errors[errorCode]), { errorCode }) } exports.errorHandler = (err, req, res, next) => { if(!err.status && err.errorCode) { err.status = parseInt(err.errorCode.toString().substring(0, 3), 10); } let status, message if (err.status) { status = err.status message = err.message } else { status = 500; message = 'unexpected behavior, Kindly contact our support team!' } res.status(status).json({ errorCode: err.errorCode, message }) }
errors.js errors.js
module.exports = { '400_1': 'JSON payload is not valid', '400_2': 'user already registered', ... }
... const user = require('./routes/user'); const { errorHandler } = require('../utils/errors'); ... app.use('/user' , user); app.use(errorHandler); ...
now with this setup, when hitting the register endpoint by postman, I only get the following in the console 现在有了这个设置,当邮递员到达注册端点时,我只能在控制台中获得以下内容
UnhandledPromiseRejectionWarning: Error: user already registered
UnhandledPromiseRejectionWarning:错误:用户已注册
could someone please tell me what am I missing here? 有人可以告诉我我在这里想念什么吗? thanks in advance!
提前致谢!
You're not catching the error which you throw inside your errorThrower
, thus getting the error UnhandledPromiseRejectionWarning
. 您没有捕获到在
errorThrower
内部抛出的错误,因此得到了错误UnhandledPromiseRejectionWarning
。 What you need to do is catch the error and pass it on the the next middleware, in order for the errorHandler
-middleware to be able to actually handle the error. 您需要做的是捕获错误,然后将其传递给下一个中间件,以使
errorHandler
-middleware能够实际处理该错误。 Something like this: 像这样:
exports.register = async(req, res) => {
try {
await registerNewUser(req.body);
} catch(err) {
next(err);
}
};
If you don't want to do this for every middleware, you could create a "base"-middleware which handles this: 如果不想对每个中间件都这样做,则可以创建一个“基本”中间件来处理:
const middlewareExecutor = async (req, res, next, fn) => {
try {
return await fn.call(fn, req, res, next);
} catch (err) {
next(err);
}
};
Now you can pass your middlewares as an argument and delegate handling the error to the executor: 现在,您可以将中间件作为参数传递,并将处理错误的委托委托给执行者:
app.use('/user' , async (req, res, next) => middlewareExecutor(req, res, next, user));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.