【问题标题】:How to catch and handle error response 422 with Redux/Axios?如何使用 Redux/Axios 捕获和处理错误响应 422?
【发布时间】:2016-12-12 09:55:08
【问题描述】:

我有一个操作向服务器发出 POST 请求以更新用户密码,但我无法处理链式 catch 块中的错误。

return axios({
  method: 'post',
  data: {
    password: currentPassword,
    new_password: newPassword
  },
  url: `path/to/endpoint`
})
.then(response => {
  dispatch(PasswordUpdateSuccess(response))
})
.catch(error => {
  console.log('ERROR', error)
  switch (error.type) {
    case 'password_invalid':
      dispatch(PasswordUpdateFailure('Incorrect current password'))
      break
    case 'invalid_attributes':
      dispatch(PasswordUpdateFailure('Fields must not be blank'))
      break
  }
})

当我记录错误时,这就是我所看到的:

当我检查网络选项卡时,我可以看到响应正文,但由于某种原因我无法访问这些值!

我是不是在不知不觉中犯了一个错误?因为我可以很好地处理来自不同请求的其他错误,但似乎无法解决这个问题。

【问题讨论】:

  • axios & catch & error.response

标签: javascript reactjs redux axios


【解决方案1】:

例子

getUserList() {
    return axios.get('/users')
      .then(response => response.data)
      .catch(error => {
        if (error.response) {
          console.log(error.response);
        }
      });
  }

检查错误对象的响应,它将包含您要查找的对象,以便您可以执行error.response.status

https://github.com/mzabriskie/axios#handling-errors

【讨论】:

  • 正是我需要的!谢谢
  • 是的!访问 err.response 得到我需要的东西,谢谢!
【解决方案2】:

Axios 可能正在解析响应。我在我的代码中访问这样的错误:

axios({
  method: 'post',
  responseType: 'json',
  url: `${SERVER_URL}/token`,
  data: {
    idToken,
    userEmail
  }
})
 .then(response => {
   dispatch(something(response));
 })
 .catch(error => {
   dispatch({ type: AUTH_FAILED });
   dispatch({ type: ERROR, payload: error.data.error.message });
 });

来自文档:

请求的响应包含以下信息。

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {}
}

所以catch(error => ) 实际上就是catch(response => )

编辑:

我仍然不明白为什么记录错误会返回该堆栈消息。我试着像这样记录它。然后你实际上可以看到它是一个对象。

console.log('errorType', typeof error);
console.log('error', Object.assign({}, error));

EDIT2:

再环顾四周this 是您要打印的内容。这是一个 Javascipt 错误对象。然后,Axios 会通过配置、代码和响应(如 this)来增强此错误。

console.log('error', error);
console.log('errorType', typeof error);
console.log('error', Object.assign({}, error));
console.log('getOwnPropertyNames', Object.getOwnPropertyNames(error));
console.log('stackProperty', Object.getOwnPropertyDescriptor(error, 'stack'));
console.log('messageProperty', Object.getOwnPropertyDescriptor(error, 'message'));
console.log('stackEnumerable', error.propertyIsEnumerable('stack'));
console.log('messageEnumerable', error.propertyIsEnumerable('message'));

【讨论】:

  • 感谢您的详细回复,我浏览了有帮助的存储库代码。最终,我记录了该对象并能够看到响应对象并处理数据。附加代码:let e = {...error}switch (e.response.data.type)
【解决方案3】:

这是处理error 对象的正确方法:

axios.put(this.apiBaseEndpoint + '/' + id, input)
.then((response) => {
    // Success
})
.catch((error) => {
    // Error
    if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        // console.log(error.response.data);
        // console.log(error.response.status);
        // console.log(error.response.headers);
    } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
        // http.ClientRequest in node.js
        console.log(error.request);
    } else {
        // Something happened in setting up the request that triggered an Error
        console.log('Error', error.message);
    }
    console.log(error.config);
});

来源网址https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253

【讨论】:

    【解决方案4】:
    axios.post('http://localhost:8000/api/auth/register', {
        username : 'test'
    }).then(result => {
        console.log(result.data)
    }).catch(err => {
        console.log(err.response.data)
    })
    

    添加捕获 得到错误响应 ==> err.response.data

    【讨论】:

      【解决方案5】:

      我也被这件事难住了一段时间。我不会重复太多,但我认为添加我的 2 美分对其他人会有所帮助。

      上面代码中的errorError 类型。发生的情况是在错误对象上调用 toString 方法,因为您正试图将某些内容打印到控制台。这是隐含的,是写入控制台的结果。如果你看一下错误对象上toString的代码。

      Error.prototype.toString = function() {
        'use strict';
      
        var obj = Object(this);
        if (obj !== this) {
          throw new TypeError();
        }
      
        var name = this.name;
        name = (name === undefined) ? 'Error' : String(name);
      
        var msg = this.message;
        msg = (msg === undefined) ? '' : String(msg);
      
        if (name === '') {
          return msg;
        }
        if (msg === '') {
          return name;
        }
      
        return name + ': ' + msg;
      };
      

      所以你可以在上面看到它使用内部构造字符串以输出到控制台。

      在 mozilla 上有很棒的 docs

      【讨论】:

        【解决方案6】:

        你可以像这样使用内联 if else 语句:

        .catch(error => {
            dispatch({
                type: authActions.AUTH_PROCESS_ERROR,
                error: error.response ? error.response.data.code.toString() : 'Something went wrong, please try again.'
            }); 
        });
        

        【讨论】:

          【解决方案7】:

          唯一对我有帮助的是以下几点:

          axios.put('/api/settings', settings, {
            validateStatus: status => status >= 200 && status < 300 || status === 422
          })

          https://stackoverflow.com/a/66285529/5849569

          【讨论】:

            猜你喜欢
            • 2021-05-22
            • 1970-01-01
            • 2020-12-16
            • 2017-02-21
            • 2016-09-01
            • 1970-01-01
            • 2016-05-28
            • 2012-07-25
            • 2019-08-31
            相关资源
            最近更新 更多