首頁 >web前端 >js教程 >如何在 Redux 和 redux-promise-middleware 中使用 Fetch 處理非 OK 狀態代碼?

如何在 Redux 和 redux-promise-middleware 中使用 Fetch 處理非 OK 狀態代碼?

DDD
DDD原創
2024-11-15 14:52:021020瀏覽

How to Handle Non-OK Status Codes with Fetch in Redux and redux-promise-middleware?

Fetch: Handling Non-OK Status Codes with Rejection and Error Catching

The provided code utilizes the 'whatwg-fetch' polyfill within Redux and redux-promise-middleware for data retrieval. However, the issue lies in handling non-OK status codes (4xx and 5xx), as Fetch promises typically only reject on network errors.

Rejection Handling

To ensure rejection of the promise with a custom error message for non-OK status codes, consider the following approach:

import 'whatwg-fetch';

function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                .then(res => res.json())
                .then(data => {
                    if (!res.ok) {
                        throw new Error(`Non-OK status code: ${res.status}`);
                    }
                    return data;
                })
                .catch(error => {
                    throw error;
                })
        });
    };
}

Error Catching

Within the action creator, an error is thrown when the response status is non-OK, and this error can be caught when handling the action in the reducer.

Sample Reducer:

case 'FETCH_VEHICLE': {
    return {
        ...state,
        isLoading: true,
    };
}
case 'FETCH_VEHICLE_FULFILLED': {
    return {
        ...state,
        isLoading: false,
        vehicle: action.payload,
    };
}
case 'FETCH_VEHICLE_REJECTED': {
    return {
        ...state,
        isLoading: false,
        error: action.payload,
    };
}

In this updated code, the payload of the 'FETCH_VEHICLE_REJECTED' action will contain the error message created in the action creator. This allows for proper error handling and display within the application.

以上是如何在 Redux 和 redux-promise-middleware 中使用 Fetch 處理非 OK 狀態代碼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn