Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 914
Konrad Klimczak Avatar asked Jan 25 '17 15:01

Konrad Klimczak


People also ask

What error does Axios throw?

By default, the axios HTTP library throws an error anytime the destination server responds with a 4XX / 5XX error (for example, a 400 Bad Request ). Since axios raises an error, your workflow will stop at this step.

How do you handle Axios requests?

To perform an HTTP POST request in Axios, call axios. post() . Making a POST request in Axios requires two parameters: the URI of the service endpoint and an object that contains the properties you wish to send to the server. For a simple Axios POST request, the object must have a url property.


2 Answers

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
like image 199
John Wundes Avatar answered Sep 28 '22 12:09

John Wundes


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

err.data.message
like image 30
Konrad Klimczak Avatar answered Sep 28 '22 12:09

Konrad Klimczak