Reputation: 19640
i have written a node.js api using the express framework. I am using await and async. I catch the asynchronous function in a try catch block. However in the catch(err) method the err is not being returned.
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"
});
}
In the above example i am deliberately calling a function that does not exist so that it throws an error.
The response i get is below. It is hitting the catch block, but the error is not being added to the data object.
{
"success": false,
"status": 500,
"data": {},
"message": "The server threw an unxpected errror"
}
However, if i move the below line out of the try catch block. The console will throw the following error.
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>
So my question is, why is this error not being displayed in the response when the call is made within the try catch block.
Upvotes: 0
Views: 1224
Reputation: 3543
By default, The error object is not JSON.stringify()
-able. Read Here
To get the stack trace however, you can use err.stack
like so:
return res.status(500).json({
success: false,
status: 500,
data: err.stack,
message: "The server threw an unxpected errror"
});
Upvotes: 3