aribouius / jsonapi-react

A minimal JSON:API client and React hooks for fetching, updating, and caching remote data.
MIT License
149 stars 28 forks source link

Error handling for 401 unauthorized responses #40

Closed widox closed 2 years ago

widox commented 3 years ago

I'm running into an issue in how to capture 401 responses from the API. It looks like the internal fetch call doesn't handle cases where the body is empty and so the res.json() call fails and that's what is returned in the error object.

Example error object for a 401 response

{
  status: "500",
  title: "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data",
  name: "SyntaxError"
}

I've tried to use formatError but that just gives me the same object as I pasted above; same thing when registering a subscriber. Is there a better way to handle this scenario?

aribouius commented 3 years ago

@widox yeah I can see how this scenario is not handled properly. It's currently assuming the API will always return a JSON:API compliant response, with the exception of a 204 status code.

I'm not quite sure what the best solution here is. Ideally the library should return whatever errors the API returned, but in the case of an empty body we have to distinguish between that and an invalid JSON body.

Perhaps something like this would work?

fetch(uri, options).then(res => {
  if (res.status === 204) {
    return {}
  }
  if (res.ok) {
    return res.json()
  }
  return res.text().then(text => {
    if (text) {
      return JSON.parse(text)
    }
    return {
      status: res.status,
      title: res.statusText,
      name: res.statusText,
    }
  })
})