Node.js-未返回Try-Catch错误
我已经使用express框架编写了node.js api。我正在使用wait和async。我在try-catch块中捕获异步函数。但是,在catch(err)方法中,不会返回errNode.js-未返回Try-Catch错误,node.js,express,async-await,try-catch,Node.js,Express,Async Await,Try Catch,我已经使用express框架编写了node.js api。我正在使用wait和async。我在try-catch块中捕获异步函数。但是,在catch(err)方法中,不会返回err try { const job = await this.jobRepository.functionDoesNotExist(); if (job.success === false) { return res.status(404
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>
const job=wait this.jobRepository.functionDoesNotExist();
“error”:{},“level”:“error”,“message”:“uncaughtException:this.jobRepository.functionDoesNotExist不是函数\n错误:this.jobRepository.functionDoesNotExist不是JobController上的函数。
因此,我的问题是,当在try-catch块中进行调用时,为什么响应中没有显示此错误。默认情况下,错误对象不是
JSON.stringify()
-able
但是,要获取堆栈跟踪,可以使用err.stack
如下所示:
return res.status(500).json({
success: false,
status: 500,
data: err.stack,
message: "The server threw an unxpected errror"
});
默认情况下,错误对象不可
JSON.stringify()
-able
但是,要获取堆栈跟踪,可以使用err.stack
如下所示:
return res.status(500).json({
success: false,
status: 500,
data: err.stack,
message: "The server threw an unxpected errror"
});