我知道如何使用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 })我的方法有什么问题,为什么我们应该使用抛出?
发布于 2017-07-30 22:11:42
您通常根本不希望在Express中抛出错误,因为除非它被捕获,否则它将导致进程崩溃,而不会给用户发出警告,而且捕获错误并维护请求上下文也不容易,否则就会这样做。
相反,Express处理程序应该在直接返回错误响应(如示例中所示)和调用next(err)之间进行选择。在我的应用程序中,我总是使用后者,因为它让我可以设置错误处理中间件来始终一致地处理各种问题。
示例如下:
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中的几乎所有内容都是通过中间件完成的。
https://stackoverflow.com/questions/45400465
复制相似问题