【问题标题】:axios cannot access message of an erroraxios 无法访问错误消息
【发布时间】:2017-06-10 19:44:12
【问题描述】:

我有一个使用 axios get 方法的函数,并且在承诺返回时,我添加了错误处理来处理我尝试连接的服务已被禁用的情况。

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

当我使用 curl 时,我可以看到消息,响应状态为 403:

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

问题是,当我尝试访问“消息”属性时,我什么也得不到,但我知道它就在那里! (我也尝试过使用 err.response.data 也没有成功)

根据文档,我应该可以访问它:axios handling errors

访问此消息的正确方法是什么?

【问题讨论】:

    标签: javascript node.js error-handling axios


    【解决方案1】:

    我查看了他的代码,似乎正确的响应在错误中,但在 axios 中,settle.js 用通用响应掩盖了它。您可以通过将 catch 块中的错误对象记录为字符串化 JSON 来查看服务器响应:

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

    所以在我的情况下,我通过访问返回的错误来修复它:

    error.response.data.message
    

    【讨论】:

    • 这也取决于服务器端。我在 Python 和 Flask 中有我的服务器端,结果发现错误消息没有发送(我有一个 try-catch 并且在 catch 块中我重新引发了相同的异常)。注册错误处理程序后,如此处flask.pocoo.org/docs/0.12/patterns/apierrors 所述,错误消息可在此答案中访问。
    【解决方案2】:

    我的 catch 函数收到的是响应属性而不是错误对象。因此,要访问我使用过的消息:

    err.data.message
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 2020-12-25
      • 2018-02-06
      相关资源
      最近更新 更多