meilisearch / meilisearch-js

JavaScript client for the Meilisearch API
https://www.meilisearch.com
MIT License
703 stars 85 forks source link

Fetch error handling is incorrect #1655

Open flevi29 opened 1 month ago

flevi29 commented 1 month ago

In the code below we're assuming that if response.json() throws an error, it means we have a communication error. This is incorrect, it will only throw if the request body isn't valid JSON (https://fetch.spec.whatwg.org/#dom-body-json). As long as we can be 100% sure that Meilisearch client will only respond with a valid JSON error body text, this will never throw. If that isn't the case, maybe we should instead use response.text().

https://github.com/meilisearch/meilisearch-js/blob/cd61a8c14e9897c975ef2176bf5e6c56d15621f3/src/errors/http-error-handler.ts#L5-L26

A communication error, or a network error would rather occur in the code below, before it gets to httpResponseErrorHandler, as described in the docs, and would be caught below and processed by httpErrorHandler.

A fetch() promise only rejects when the request fails, for example, because of a badly-formed request URL or a network error. A fetch() promise does not reject if the server responds with HTTP status codes that indicate errors (404, 504, etc.). Instead, a then() handler must check the Response.ok and/or Response.status properties.

https://github.com/meilisearch/meilisearch-js/blob/cd61a8c14e9897c975ef2176bf5e6c56d15621f3/src/http-requests.ts#L165-L174

Now, this httpErrorHandler messes with the error in such a way that information gets lost, which is another bug in itself, related to and detailed in #1612, and that's another issue that I should probably address separately.