Joldnine / joldnine.github.io

My github.io blog repo. https://joldnine.github.io
2 stars 1 forks source link

Fetch API's Error Handling #29

Open Joldnine opened 5 years ago

Joldnine commented 5 years ago

Error handling of Fetch API will be much different from the way of ajax.

Normally, when the back end returns a non 200 response, the front end may either deal with the response's statusText or the response's body.

Here are the snapshots (in our example, the response body is json):

  1. response.statusText
fetch(query).then((response) => {
  if (!response.ok) {
    throw Error(response.statusText);
  }
  response.json().then((response) => {
    console.log(response)
  })
}).catch((error) => {
  // caution: error (which is response.statusText) is a ByteString, so we may need to convert it to string by error.toString()
  console.log(error.toString())
})
  1. response.body
fetch(query).then((response) => {
  if (!response.ok) {
    response.json().then((error) => {
      throw Error(error);
    }).catch(error => {
      console.log(error.message)
    })
  } else {
    response.json().then((response) => {
      console.log(response)
    })
  }
})