在 axios catch 子句中访问 HTTP 错误正文数据 [重复]

Posted

技术标签:

【中文标题】在 axios catch 子句中访问 HTTP 错误正文数据 [重复]【英文标题】:Accessing the HTTP error body data in an axios catch clause [duplicate] 【发布时间】:2021-11-19 01:35:19 【问题描述】:

当我的 API 报告客户端应该很好地处理的错误时,我想使用 HTTP 错误。在我的 400 API 响应中,我将正文设置为错误元数据,但我的所有 axios catch 语句返回的是一个通用的 400 错误字符串,而不是我可以检查和处理错误的响应对象。

例子

  function (ent) 
        return axios
          .post(config.ROOT_API + '/api/backstory/', new_parent_entity: ent, child_entity: this.entity)
          .then((data) => 
            console.log(data)
          )
          .catch((e) => 
            console.log(e) // this returns
          )

e 作为堆栈跟踪返回:

BackstoryUpdate.vue?8720:191 Error: Request failed with status code 400
    at createError (createError.js?2d83:16)
    at settle (settle.js?467f:17)
    at XMLHttpRequest.handleLoad (xhr.js?b50d:62) 

而 400 响应包含我想要访问的这个正文,例如:

error: "Circular reference detected", container: id: 39, text: "abdef"

【问题讨论】:

哎呀,是的,谢谢。我会关门的。 另见***.com/q/45017822/3001761, npmjs.com/package/axios#handling-errors, ... 【参考方案1】:

您需要在错误中访问响应对象。

function (ent) 
    return axios
      .post(config.ROOT_API + '/api/backstory/', new_parent_entity: ent, child_entity: this.entity)
      .then((data) => 
        console.log(data)
      )
      .catch((e) => 
        console.log(e.response) // this returns
      )

【讨论】:

以上是关于在 axios catch 子句中访问 HTTP 错误正文数据 [重复]的主要内容,如果未能解决你的问题,请参考以下文章