抛出错误与快递中的正常退货

时间:2017-07-30 13:45:43

标签: javascript node.js api express

我知道如何使用node.js(express)编写简单的API。但现在我感到困惑,无法区分这两段代码

if(err){ return res.status(500).json(err) }
return res.json(result)

if(err) { throw new Error(err) }
return res.json(result)

API响应的标准是什么?我只返回2个属性,比如

if(err){ return res.json({ status: false, msg: 'user password is incorrect }) }
return ({ status: true, msg: result.token })

我的方法有什么问题以及我们为什么要使用throw?

1 个答案:

答案 0 :(得分:0)

你根本不想在Express中抛出错误,因为除非它被捕获,否则会使进程崩溃而不会向用户发出警告,并且捕获错误并维护请求上下文并不容易。

相反,Express处理程序中的选择应该在直接返回错误响应(如示例中)和调用next(err)之间。在我的应用程序中,我总是执行后者,因为它允许我设置错误处理middlware以始终如一地处理各种问题情况。

以下示例:

app.get('/something', (req, res, next) => {
  // whatever database call or the like
  Something.find({ name: 'something'}, (err, thing) => {
     // some DB error, we don't know what. 
     if (err) return next(err);
     // No error, but thing wasn't found
     // In this case, I've defined a NotFoundError that extends Error and has a property called statusCode set to 404. 
     if (!thing) return next(new NotFoundError('Thing was not found'));
     return res.json(thing);
  });
});

然后一些中间件处理错误,如:

app.use((err, req, res, next) => {
  // log the error; normally I'd use debug.js or similar, but for simplicity just console in this example
  console.error(err);

  // Check to see if we have already defined the status code
  if (err.statusCode){
    // In production, you'd want to make sure that err.message is 'safe' for users to see, or else use a different value there
    return res.status(err.statusCode).json({ message: err.message }); 
  }
  return res.status(500).json({ message: 'An error has occurred, please contact the system administrator if it continues.' });
});

请注意,Express中的几乎所有内容都是通过中间件完成的。