0

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.

1 Answer 1

3

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"
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.