matthew-andrews / isomorphic-fetch

Isomorphic WHATWG Fetch API, for Node & Browserify
MIT License
6.95k stars 289 forks source link

How to handle error messages from server - Question #193

Closed mylastore closed 3 years ago

mylastore commented 3 years ago

I can not find anything on the web on how to handle actual error messages from the server. I don't just want to display response.statusText or response.status. Does anyone have an example?

matthew-andrews commented 3 years ago

It's entirely up to you … personally I would do something like this:

if (response.ok) {
  // proceed with normal logic
}
switch (response.status) {
  case 404:
    throw new NotFoundError();
  default:
    throw new UnexpectedError();
}

then handle the errors appropriately elsewhere in my code.


try {
  await retrieveAndDisplayData();
} catch(err) {
  if (err instanceof NotFoundError) {
    // handle the case of the data not found
  } else if (err instanceof UnexpectedError) {
    // potentially log the error to an aggregation system (e.g. Sentry)
    // and inform the user that an unexpected error has occurred
    // and potentially offer the them the option of a retry
  }
  // another, truly unexpected, error so throw
  throw err;
}