Konrad Klimczak
Konrad Klimczak

Reputation: 1534

axios cannot access message of an error

I have a function which use axios get method and on the promised returned I have added error handling to handle a situation when service I am trying to connect to has been disabled.

axios.get('/someurl')
    .then(() => {
        // this does not matter
    })
    .catch((err) => {
        logger.error(TAG, 'postCreateVm', err);
        return reply(Boom.forbidden(err.message));
    });

When I use curl I can see the message, status of response is 403:

# curl -X GET localhost:3000/someurl
{
    "message": "abort"
}

The problem is that when I try to access 'message' property i get nothing, but I know it's there! (I have tried to use err.response.data as well with no success also)

According to the documentation I should be able to access it: axios handling errors

What is the proper way to access this message?

Upvotes: 8

Views: 7592

Answers (2)

Konrad Klimczak
Konrad Klimczak

Reputation: 1534

My catch function received the response property instead of error object. So, to access message I had use:

err.data.message

Upvotes: 2

John Wundes
John Wundes

Reputation: 264

I've looked at his code, and it appears the correct response is in the error, but in axios, settle.js masks it with a generic response. You can see the server response by logging the error object in your catch block as stringified JSON:

console.log('caught:::', JSON.stringify(response, null, 2))

So in my case, I fixed it by accessing the returned error as:

error.response.data.message

Upvotes: 19

Related Questions