mswjs / msw

Seamless REST/GraphQL API mocking library for browser and Node.js.
https://mswjs.io
MIT License
15.73k stars 506 forks source link

Allow customization of network error #2156

Closed Lesstat closed 4 months ago

Lesstat commented 4 months ago

Scope

Improves an existing behavior

Compatibility

Feature description

As of version 2.3.0 (or PR #2135 respectively) errors in request handlers are no longer treated as network errors but as server errors. Therefore, it is no longer possible to write tests with msw for reacting to specific network errors.

I request (re-)introducing the possibility to throw custom network errors. Possible API might look like this:

http.get('/resource', () => {
  const customError = { some: 'error' };
  return HttpResponse.error(customError)
})
kettanaito commented 4 months ago

Hi, @Lesstat. Thanks for raising this!

This has been brought up in the past, and I've decided not to support custom error messages with HttpResponse.error(). There are two reasons for it.

Reason 1: Response.error()

The HttpResponse.error() static method is modeled after the standard Response.error(), which does not support any arguments, representing a generic network error when processing a request. Staying consistent here means predictable behavior, and I value that quite a lot.

Reason 2: Inconsistent error handling

MSW v1 used to have a NetworkError class that supported custom error messages. It has quickly taught us that it is up to the request client to forward that error message to you, and some widely-used clients do not do that at all. This results in inconsistent errors, degrading the experience (and also producing different behavior based on what request client you're using, which we are trying to eliminate here at MSW).

I hope this gives you some insight as to why this wouldn't be a good idea to introduce.

When I stumbled upon your issue, I also noticed that we still recommended throwing errors in response resolvers in the docs. I've updated the HttpResponse.error() page, also providing a short summary as to why we are not supporting custom error messages.