Javascript 如何使用 Redux/Axios 捕获和处理错误响应 422?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38798451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:52:16  来源:igfitidea点击:

How to catch and handle error response 422 with Redux/Axios?

javascriptreactjsreduxaxios

提问by Phillip Boateng

I have an action making a POSTrequest to the server in order to update a user's password, but I'm unable to handle the error in the chained catch block.

我有一个操作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
  }
})

When I log the error this is what I see:

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

Error Logged

错误记录

When I check the network tab I can see the response body, but for some reason I can't access the values!

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

Network Tab

网络标签

Have I unknowingly made a mistake somewhere? Because I'm handling other errors from different request fine, but can't seem to work this one out.

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

采纳答案by Jeroen Wienk

Axios is probably parsing the response. I access the error like this in my code:

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 });
 });

From the docs:

从文档:

The response for a request contains the following information.

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

{
  // `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: {}
}

So the catch(error => )is actually just catch(response => )

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

EDIT:

编辑:

I still dont understand why logging the error returns that stack message. I tried logging it like this. And then you can actually see that it is an object.

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

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

EDIT2:

编辑2:

After some more looking around thisis what you are trying to print. Which is a Javascipt error object. Axios then enhances this error with the config, code and reponse like this.

再四处看看之后,就是您要打印的内容。这是一个 Javascipt 错误对象。爱可信则增强了这种错误与配置,代码和效应初探喜欢这样

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'));

回答by Steven Leggett

Example

例子

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

Check the error object for response, it will include the object you're looking for so you can do error.response.status

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

enter image description here

在此处输入图片说明

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

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

回答by Supervision

Here is the proper way to handle the errorobject:

这是处理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);
});

Origin url https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253

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

回答by Ryan-Neal Mes

I was also stumped on this for a while. I won't rehash things too much, but I thought it would be helpful to others to add my 2 cents.

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

The errorin the code above is of type Error. What happens is the toStringmethod is called on the error object because you are trying to print something to the console. This is implicit, a result of writing to the console. If you look at the code of toString on the error object.

error上面的代码的类型的Error。发生的情况是在错误对象上调用了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;
};

So you can see above it uses the internals to build up the string to output to the console.

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

There are great docson this on mozilla.

mozilla 上有关于这方面的很棒的文档

回答by Anthony Artemiev

You can use inline if else statement like so:

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

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

回答by Afdal Mtk

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

add in catch geting error response ==> err.response.data

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