thepassle / app-tools

128 stars 8 forks source link

[api] Return error Response #8

Open jfsiii opened 1 year ago

jfsiii commented 1 year ago

I want to a) not throw an error when !response.ok b) have full access to the Response (statusText, body, headers) etc

e.g. given

const response = await api.post(`/endpoint`, { bad: 'data' }`

I'd like response to always be a Response regardless of what HTTP status code was returned. Is this possible?

(a) seems to be addressed by handleError but I cannot figure out how to achieve (b). I've tried every combination of handleError, afterFetch, etc I can think of but I can never seem to get the body of an error response back (e.g. if /endpoint returns a 4xx.

Looking at the code, the issue seems to be that .then(handleStatus) is always called. And handleStatus converts that Response to an Error, losing all the info from the Response

  if (!response.ok) {
    throw new Error(response.statusText);
  }

Do I have that correct? Either way, can you suggest any way to achieve what I'm describing?

Edit: I now see that getting the Response would be a bigger change than skipping handleStatus. IIUC, skipping handleStatus would allow access to the processed body though

thepassle commented 1 year ago

I think the handleError stuff can be made a plugin as well, I think that makes sense. Would you be willing to make a pr?

thepassle commented 1 year ago

Actually, thinking more on this, instead of throwing with only the statustext, cant we just throw with the entire response object?