2017-07-30 39 views
0

我知道如何使用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?

回答

0

您通常不希望在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.' }); 
}); 

注意,几乎一切都在快速通过中间件来完成。

+0

你能显示一些代码吗?做下一步(err)会产生什么样的结果?我的大部分api都没有中间件,下一步(err)还是相关的? –

+0

你推荐什么中间件来处理错误? –

+0

我展示的那个?节点中的中间件只是一个处理函数。有时你可以通过使用模块来实现,但是你不需要。我写了praeter(https://www.npmjs.com/package/praeter)作为包装我提到的上述内容的一种方式,但您可以使用自己的代码轻松完成。 – Paul