mswjs / interceptors

Low-level network interception library.
https://npm.im/@mswjs/interceptors
MIT License
523 stars 118 forks source link

fix: add `RequestError` class #562

Closed kettanaito closed 2 months ago

kettanaito commented 2 months ago

Right now, there's no way to prevent an error from being coerces as a 500 error response. In some cases, like here, we do want to throw an error for it to error the request instead of producing an error response.

This adds a new RequestError class. If an instance of RequestError is thrown within a request listener, the respective request will error with the error thrown.

Behavior-wise, this is similar to using Response.error() as a mocked response. The difference is that you can throw RequestError anywhere in the request handling pipeline.

Now, to think of it, we can achieve the same behavior by throw Response.error(). Right now, though, that won't work because a thrown Response is always forwarded to .respondWith() as-is, which is incorrect in the case of Response.error(). In other words, we are only handling Response.error() if it's provided to request.respondWith(), not thrown.

kettanaito commented 2 months ago

This is potentially solved by adding support for throwing Response.error() (https://github.com/mswjs/interceptors/pull/563).

kettanaito commented 2 months ago

Not needed.

566 allows you to opt-out from the default exception handling. In the future, controller.errorWith() will allow you to mock request errors explicitly (see #431).