Capturing Responses other than 200 OK From Fetch

Viewed 8227

I'm using the native fetch library as specified here. It seems that whenever a response other than a 200 OK is returned it throws an exception with the string response Uncaught (in promise) TypeError: Failed to fetch.

Was there a way to catch and branch on specific HTTP response codes and still view the response data? For example a 401 response?

I have attached my request code I am using as a wrapper for fetch.

static request(url, data) {

    let headers = {
        "Authorization": window.localStorage.getItem("Authorization"),
        "Content-Type": "application/json"
    };

    let options = {
        method: "GET",
        headers: headers,
        mode: "no-cors",
        cache: "no-cache",
    };

    if (data) {
        options = {
            method: "POST",
            headers: headers,
            mode: "no-cors",
            cache: "no-cache",
            body: JSON.stringify(data)
        }
    }

    return new Promise(async (resolve, reject) => {

        try {

            let response = await fetch(url, options);
            let jsonResponse = await response.json();
            return resolve(jsonResponse);

        } catch (error) {
            // hashHistory.push("/login");
            return reject(error);
        }

    })

}   
2 Answers
Related