简体   繁体   中英

Fetch api handle and read error responses

I have following fetch API call in JavaScript

async doCheckin(authCode) {
    return await fetch(endpoint + "/checkin", {
        method: "put",
        headers: new Headers({'content-type': 'application/json'}),
        body: JSON.stringify({authCode: authCode})
    })
        .then(this.checkStatus)
        .then(this.toJson)
        .catch(function (error) {
            console.error("Checkin not successful");
            throw error;
        });
}

async checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return Promise.resolve(response)
    } else {
        let errorJson = await response.json();
        return Promise.reject(errorJson.code);
    }
}

toJson(response) {
    return response.json()
}

The function is called like this

   let checkIn = (await apiService.doCheckin(code)
        .catch(displayError));

This call should handle error responses in JSON from the server and display an error code. I have noticed that some in-app mobile browsers can not handle the error case and fail at let errorJson = await response.json();

Is this a correct way to handle and read error responses or is there any better way to achieve this?

The problem with using this:

let errorJson = await response.json();

is that you are not handling the case where the method call json() fails. Instead you should be doing something like this where you handle it.

try {
  let errorJson = await response.json();

  return Promise.reject(errorJson.code);
} catch (e) {
  // I don't know what error is occurring so just reject with a 503 
  return Promise.reject('503');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM