【问题标题】:How to handle api errors using aws-amplify?如何使用 aws-amplify 处理 api 错误?
【发布时间】:2018-09-12 23:31:09
【问题描述】:

我目前正在尝试使用 aws-amplify react lib 将数据发布到由 aws api-gateway 触发的我的 aws lambda 函数。

代码如下:

API.post("snippets","snippets/", {
        body: data,
    }).then(response => response).catch(console.log(err))

在主要情况下,一切正常。

但我的 lambda 函数旨在验证输入数据并返回状态码 400,返回的有效负载如下所示:

{
    "errors": [
        {
            "field": "title",
            "message": "This field is required"
        }
    ]
}

我想捕捉这些错误以便在前端显示它们,但aws-amplify 似乎有一个未记录的行为。

默认情况下,返回的状态码400会抛出默认错误消息:

Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)

有没有办法获取返回的有效载荷而不是这个神奇的错误?

【问题讨论】:

    标签: reactjs amazon-web-services aws-lambda amazon-cognito aws-amplify


    【解决方案1】:

    事实证明,在后台,aws-amplify使用 Axios 进行 http 调用。

    使用Axios时,必须console.log(error.response):https://github.com/axios/axios/issues/960

    这是我所做的修复:

    API.post("snippets","snippets/", {
            body: data,
        }).then(response => response).catch(error => console.log(error.response.data))
    

    aws-amplify 文档上的拉取请求已打开:https://github.com/aws/aws-amplify/pull/633

    【讨论】:

    • 这对当前版本的放大仍然有效吗?我似乎没有收到Error.response 属性。
    • 我也遇到了没有error.response 属性的问题,我想我们可能需要在某个时候更新它
    • 这对我有用,但是现在我必须更新我的整个应用程序。有没有办法从服务器端发送它,我可以使用error.message 而不是error.response.data.message。我正在使用放大快递服务器
    • 我正在使用 Amplify v6.2.1,这个答案对我有用。
    【解决方案2】:

    我也遇到了类似的问题,它显示了默认的错误消息“请求失败,状态码 400”,而不是 API 返回的消息。

    我记录了错误对象,但它没有在其中显示响应属性。但是我们确实有响应属性。我尝试记录 Error.response,它确实包含从 API 发送的响应。

    【讨论】:

      【解决方案3】:

      刚刚通过'Cancel API requests' Amplify docs 发现了这一点。

      据我所知,这是 API 调用返回的错误对象的内容:

      我正在做的只是打印出错误,显然你会在这里做更多的事情,但这是一个好的开始。

      async uploadUser(state, payload) {
      
      const promise = API.graphql({
          query: createUser,
          variables: { input: payload },
      });
      
      try {
          await promise;
      } catch (error) {
          // Print out the actual error given back to us.
          console.log(error.errors[0].message);
          
          // If the error is because the request was cancelled we can confirm here.
          if (API.isCancel(error)) {
      
              // handle user cancellation logic.
              console.log(error.message);
              
          }
      }
      

      希望对你有帮助?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-09-27
        • 2021-11-16
        • 2020-05-10
        • 2021-03-23
        • 1970-01-01
        • 2018-01-15
        • 1970-01-01
        • 2020-04-29
        相关资源
        最近更新 更多