我有一个辅助函数,可以访问 API 并按 ID 获取页面。它使用 async/await,我正在尝试使用 try catch 处理错误。
为了测试错误处理,我故意给它一个不存在的 ID。
方法如下:
const findPage = async (req, res, pageId) => {
let document
try {
let response = await getByID(pageId)
if (!response) throw Error('No Response')
return document
} catch (error) {
console.log(error) // I can see the error is being thrown.. I am purposefuly giving it an id that does not exist
return error
}
}
它确实像我预期的那样抛出错误。但是,我使用快速路由在应用程序的另一部分调用该函数。
Router.route('/page/:id').get(async (req, res) => {
let results
try {
results = await findPage(req, res, req.params.id) // This Function Returns an error
// Yet we still get results
res.json({results, msg: 'WHY?'})
} catch (error) {
res.send(error)
}
})
在同一个路由器文件中,我也尝试向该路由器添加一些特定的中间件,但由于没有错误,因此永远不会触发它。
Router.use((err, req, res, next) => {
if (err) {
console.log('holy error')
} else {
console.log('no error')
}
next(err)
})
当 Express API 调用本身返回错误时,它如何返回结果而不是错误?
最佳答案
我从您的代码中看到的是,您的 Router.route
内的 try/catch block 没有捕获 findPage
函数的 expetion,那是因为您还在 findPage
中捕获异常,并且只是简单地返回错误而不是抛出异常;
try {
results = await findPage(req, res, req.params.id) // This Function Returns an error
// Yet we still get results
res.json({results, msg: 'WHY?'})
} catch (error) {
res.send(error)
}
因此,在 findPage
中,如果您确实需要在发生异常时执行某些操作,那么您必须捕获它,如果您希望调用者也捕获该异常,您需要抛出相同的错误或新的错误再次出现上下文感知错误。否则,如果发生异常时不执行任何操作,则不需要捕获它。
const findPage = async (req, res, pageId) => {
let document
try {
let response = await getByID(pageId)
if (!response) throw Error('No Response')
return document
} catch (error) {
// do something here if you really need to otherwise you dont need to catch exceptions here
// then rather than `return error` you should
throw error
}
}
关于node.js - 异步函数抛出错误 - 但调用它的快速端点 - 看不到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50751243/