如何让NodeJS和ExpressJS抛出错误?

3
该 Web 应用程序使用 Express 作为服务器,Node.js 作为语言,MongoDB 作为数据库,mongoose 作为包装器。Express 在端口 3000 上运行服务器,我正在尝试为集合实现基本的 CRUD 操作。我使用 Newrelic 生成图表,并且当 Express 抛出错误时,响应时间会上升。例如:
User.findOne({ $or: [{ email: { $regex: new RegExp(email, 'i') } }, { userLogin: { $regex: new RegExp(userLogin, 'i') } }] }, 'id').exec()
    .then(results => {
        if (results) { throw new APIError('email_taken') } 
        else { return results }
  }).then(result => {
      res.status(201).success(result)
    }, error => {
      res.error(error)
    })

我真的不理解为什么当ExpressJS抛出像这样的错误时,服务器时间会上升。 我想知道是否我的方法有误或是否有其他更好的方法。 谢谢。

1个回答

0

如果您查看ExpressJS文档中的错误处理,它指出:

在路由处理程序和中间件中发生的同步代码错误无需额外工作。如果同步代码引发错误,则Express将捕获并处理它。

但是

对于由路由处理程序和中间件调用的异步函数返回的错误,您必须将它们传递给next()函数,Express将捕获并处理它们。

由于数据库操作本质上是异步的,因此您应始终将错误传递给next()以正确处理它

例如

app.get("/", function (req, res, next) {
  fs.readFile("/file-does-not-exist", function (err, data) {
    if (err) {
      next(err); // Pass errors to Express.
    }
    else {
      res.send(data);
    }
  });
});

我真的使用它app.use(function (req, res, next) { res.setHeader('Content-Type', 'application/json') res.success = function (obj) { res.send(APIResponse(obj)) } res.error = function (param1, param2) { let error if (param1.constructor === APIError) { error = param1 } else if (typeof (param1) === 'string') { error = new APIError(param1, param2) } else { error = new APIError('unknown') } res.status(error.status).send({ 'success': false, 'error': { 'code': error.code, 'message': error.message } }) } next() }) - Haythem Hedfi
你说你用它是什么意思?我已经查看了你所注释的代码,但我的意思是,由于任务的异步性质,将错误传递给next()。 - PrivateOmega
你能修正这段代码吗?User.findOne({ $or: [{ email: { $regex: new RegExp(email, 'i') } }, { userLogin: { $regex: new RegExp(userLogin, 'i') } }] }, 'id').exec() .then(results => { if (results) { throw new APIError('email_taken') } else { return results } }).then(result => { res.status(201).success(result) }, error => { res.error(error) }) - Haythem Hedfi
module.exports.login = function (req, res, next) { User.findOne({ $or: [{ 'auth.local.email': emailOrUserLogin }, { 'auth.local.userLogin': emailOrUserLogin }] }).exec() .then(results => { if (results) { return results } else { return next(new APIError('login_failed')) } }) } - Haythem Hedfi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接