最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - axios cannot access message of an error - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Jan 25, 2017 at 15:07 Konrad Klimczak asked Jan 25, 2017 at 15:00 Konrad KlimczakKonrad Klimczak 1,5342 gold badges22 silver badges47 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 19

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

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

err.data.message
发布评论

评论列表(0)

  1. 暂无评论