JavaScript >> Javascript 文檔 >  >> Tags >> Error

使用 Axios 處理錯誤

簡介

Axios 是一個 JavaScript 庫,它使用 Promise API 通過 http 創建 HTTP 請求 在 Node.js 運行時或 XMLHttpRequests 在瀏覽器中。因為這些請求是 Promise,所以它們使用較新的 async/await 語法以及 .then() 承諾鍊和 .catch() 的函數 錯誤處理機制。

try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    // Handle error
    console.log(err);
}

然後趕上

使用現代 JS 可以通過兩種方式處理 Promise - async/await 語法,如上所示,以及 .then().catch() 方法。請注意,這兩種方法都可以產生相同的功能,但 async/await 通常被認為更容易使用,並且在更長的 Promise 鏈中需要更少的樣板代碼。

下面是實現相同目標的方法,但使用 then/catch 方法:

axios.get('/my-api-route')
    .then(res => {
        // Work with the response...
    }).catch(err => {
        // Handle error
        console.log(err);
    });

reserr 對象與 async/await 語法相同。

處理錯誤

在本節中,我們將研究兩類主要問題,以及我們可能遇到的其他問題以及如何使用 Axios 管理它們。您必須了解這適用於 Axios 處理的所有類型的 HTTP 查詢,包括 GET , POST , PATCH ,等等。

在這裡你可以看到三個方面的語法——這將捕獲錯誤;需要注意的是,這個錯誤帶有一個包含大量信息的大型錯誤對象:

try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    if (err.response) {
        // The client was given an error response (5xx, 4xx)
    } else if (err.request) {
        // The client never received a response, and the request was never left
    } else {
        // Anything else
    }
}

錯誤對象的差異,在上面的 catch 中突出顯示 代碼,指示請求遇到問題的位置。我們將在以下部分對此進行深入探討。

error.response

這是我們最熟悉的錯誤類型,而且更容易處理。許多站點會根據 API 提供的內容顯示 404 Not Found 頁面/錯誤消息或各種響應代碼;這通常是通過響應來處理的。

如果您的錯誤對象具有響應屬性,則表示您的服務器返回了 4xx/5xx 錯誤。這將幫助您選擇返回給用戶的消息類型;您要為 4xx 提供的消息可能與為 5xx 提供的消息不同,並且如果您的後端根本沒有返回任何內容。

try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    if (err.response) {
        // The client was given an error response (5xx, 4xx)
        console.log(err.response.data);
        console.log(err.response.status);
        console.log(err.response.headers);
    } else if (err.request) {
        // The client never received a response, and the request was never left
    } else {
        // Anything else
    }
}

error.request

此錯誤最常見的原因是網絡不良/不穩定、後端掛起且無法立即響應每個請求、未經授權或跨域請求,以及後端 API 返回錯誤。

注意: 當瀏覽器能夠發起請求但由於任何原因未收到有效答案時,就會發生這種情況。

try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    if (err.response) {
        // The client was given an error response (5xx, 4xx)
    } else if (err.request) {
        // The client never received a response, and the request was never left
        console.log(err.request);
    } else {
        // Anything else
    }
}

前面我們提到,Axios 使用的底層請求取決於它運行的環境。 err.request 也是如此 目的。這裡是 err.request 對像是 XMLHttpRequest 的一個實例 在瀏覽器中執行時,它是 http.ClientRequest 的一個實例 在 Node.js 中使用時。

其他錯誤

錯誤對象可能沒有 responserequest 附著在它上面的物體。在這種情況下,暗示設置請求時存在問題,最終觸發了錯誤。

try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    if (err.response) {
        // The client was given an error response (5xx, 4xx)
    } else if (err.request) {
        // The client never received a response, and the request was never left
    } else {
        // Anything else
        console.log('Error', err.message);
    }
}

例如,如果您從 .get() 中省略 URL 參數,可能會出現這種情況 調用,因此沒有提出任何請求。

結論

在這篇簡短的文章中,我們研究瞭如何處理 Axios 中的各種故障和錯誤。這對於向您的應用程序/網站訪問者提供正確的消息也很重要,而不是總是返回一般錯誤消息、發送 404 或指示網絡問題。


下一篇
No
Tutorial JavaScript 教程
  1. 2021 年的 Node.js 堆轉儲

  2. 使用 WebSocket 聊天應用程序:樣板代碼

  3. 使用 Stencil 和 Storybook 構建 Web 組件庫

  4. 在 Position:Relative Container Div 中垂直和絕對水平放置一個固定的 Div

  5. 在 React 中創建自定義選擇組件(複合組件模式 + Typescript)

  6. 瀏覽器、DOM、JavaScript。構建有效的網絡應用程序所需的一切。第二部分——DOM。

  7. Plot Cheatsheets:使用 JavaScript 學習可視化的交互式筆記本

  1. 更新 jQuery UI 小部件選項

  2. 跨域 iframe 調整大小

  3. 教程 - JWT + NodeJs + MongoDB + Vue(後端 - 第二部分)

  4. 我不使用 Typescript 的原因

  5. Web 組件發生了什麼?

  6. ng-click 不適用於 ng-if

  7. 將 Chai 斷言庫與 Mocha 一起使用

  1. React/Rails 寫作挑戰應用程序的項目規劃

  2. 帶有動畫時間序列、交互式摘要和國家比較的 COVID-19 儀表板

  3. 在 Amplify 上創建業務邏輯

  4. JS 設置對象(2 個方便的用法)