我使用express框架编写了node.js api . 我正在使用await和async . 我在try catch块中捕获异步函数 . 但是在catch(err)方法中,错误不会被返回 .
try {
const job = await this.jobRepository.functionDoesNotExist();
if (job.success === false) {
return res.status(404).json({
success: false,
status: 404,
data: job,
message: "Failed to retrieve job"
});
}
return res.status(200).json({
success: true,
status: 200,
data: job.data,
message: "Successfully retrieved job"
});
} catch (err) {
return res.status(500).json({
success: false,
status: 500,
data: err,
message: "The server threw an unxpected errror"
});
}
在上面的例子中,我故意调用一个不存在的函数,以便抛出错误 .
我得到的回应如下 . 它正在命中catch块,但错误没有被添加到数据对象中 .
{
"success": false,
"status": 500,
"data": {},
"message": "The server threw an unxpected errror"
}
但是,如果我将下面一行移出try catch块 . 控制台将抛出以下错误 .
const job = await this.jobRepository.functionDoesNotExist();
"error":{},"level":"error","message":"uncaughtException: this.jobRepository.functionDoesNotExist is not a function\nTypeError: this.jobRepository.functionDoesNotExist is not a function\n at JobController.<anonymous>
所以我的问题是,为什么在try catch块中进行调用时,这个错误没有显示在响应中 .
1 回答
默认情况下,错误对象不是
JSON.stringify()
-able . Read Here但是要获得堆栈跟踪,您可以像这样使用
err.stack
: