簡體   English   中英

如何使用 Redux/Axios 捕獲和處理錯誤響應 422?

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

我有一個操作向服務器發出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
  }
})

當我記錄錯誤時,這是​​我看到的:

錯誤記錄

當我檢查網絡選項卡時,我可以看到響應正文,但由於某種原因我無法訪問這些值!

網絡標簽

我是不是在不知不覺中犯了一個錯誤? 因為我正在處理來自不同請求的其他錯誤,但似乎無法解決這個問題。

示例

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

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

編輯2:

再四處看看之后, 就是您要打印的內容。 這是一個 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'));

這是處理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

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

我也被這個問題難住了一段時間。 我不會重復太多,但我認為添加我的 2 美分對其他人會有所幫助。

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

所以你可以在上面看到它使用內部結構來構建字符串以輸出到控制台。

mozilla 上有關於這方面的很棒的文檔

您可以像這樣使用內聯 if else 語句:

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

唯一對我有幫助的是以下內容:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM