mswjs / interceptors

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

Unclear how to throw an actual error #579

Closed theoephraim closed 5 days ago

theoephraim commented 3 weeks ago

It seems all errors thrown in an interceptor are swallowed and turned into a request responses.

What if I actually just want to cancel the request altogether and throw an error? Is that even possible? I did some digging in the source and the docs but couldn't quite figure it out.

Thanks!

theoephraim commented 3 weeks ago

I figured it out - see https://github.com/mswjs/interceptors/pull/566

For anyone else coming across this, you must attach an unhandledException event listener, and then you can re-throw the error, or do whatever else you need to... In my case, wanting to throw the error, that looks like this:

interceptor.on('unhandledException', ({ error, request, requestId, controller }) => { throw error; });

I suppose the issue still stands that this was not clear, as it it does not seem to be documented. I will try to find some time to open a PR.

kettanaito commented 3 weeks ago

Hi, @theoephraim. That's certainly an oversight on my end.

Please, could you open a PR that adds a new section called "Error handling" after this block in the readme?

It would be great to mention the following things in that new section:

  1. How by default unhandled exceptions are coerced to 500 error responses.
  2. You can still listen to exceptions by providing the unhandledException event listener.
  3. If you do provide the listener, and that listener handles the request or throws the exception, it won't be coerced to 500 response. This allows you to opt-out from the default behavior (show two examples: 1 handles exceptions with a mocked response; 2 throws the error).
kettanaito commented 5 days ago

Released: v0.30.1 🎉

This has been released in v0.30.1!

Make sure to always update to the latest version (npm i @mswjs/interceptors@latest) to get the newest features and bug fixes.


Predictable release automation by @ossjs/release.