fetch icon indicating copy to clipboard operation
fetch copied to clipboard

Throws error on :accept :json when response body is empty.

Open knubie opened this issue 2 years ago • 2 comments

When you specify an :accept :json header, lambdaisland/fetch will attempt to automatically decode the response body using response.json(). However this will fail and raise an error if the response body is empty (ie JSON.parse('')). https://github.com/lambdaisland/fetch/blob/246d5615eb242ef092096b6040a1ec011682a924/src/lambdaisland/fetch.cljs#L66-L67

The code should probably check if the body is empty first.

knubie avatar Feb 23 '23 23:02 knubie

This is sadly expected behaviour when using JS Fetch: https://github.com/whatwg/fetch/issues/113

Why WHATWG didn't think this would be an issue by when they designed the API, I really have no idea. Returning 204 or 404 with no body is a common situation on the Internet and I don't think the server isn't supposed to make up imaginary content just because the client is requesting a specific content-type.

I guess this library could have a fix for us using it.

simongray avatar May 19 '23 09:05 simongray

I could see a case for a wrapper library like lambdaisland/fetch catching the error or even rethrowing a more reasonable one, but that would be an expansion to this library's scope. The code would be trivial, but semantically it would be a bit of a shift.

There is one place where we catch exceptions: https://github.com/lambdaisland/fetch/blame/926fccabfebced3340548f33e41a72b159d97678/src/lambdaisland/fetch.cljs#L106. So perhaps it wouldn't be too much of a change?

alysbrooks avatar Jul 17 '23 05:07 alysbrooks