mswjs / interceptors

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

feat: add "unhandledException" event #566

Closed kettanaito closed 2 months ago

kettanaito commented 2 months ago

Changes

Adds a new event to the HTTP events map called unhandledException. If the listener for that event is provided, whenever an unhandled exception occurs in the request listener, the unhandledException listener will be called (if present).

This allows the client to opt-out from the default handling of exceptions (producing 500 error responses), as well as do so conditionally. If the unhandledException listener does nothing, the default handling kicks in.

Note: The unhandledException listener receives a readonly request instance (non-interactive request). To affect the request, it receives an additional controller object with methods .respondWith() and .errorWith().

request.respondWith() operates on a promise basis and by the time exception occurs, that promise has been awaited already. Besides, I very much wish to move away from patching the Request instance with .respondWith() to the designated controller argument for the request listener as well. I see this as an incremental change in that direction.

interceptor.on('unhandledException', ({ error, request, requestId, controller }) => {
  controller.respondWith(new Response('fallback response'))
  // controller.errorWith(new Error('fallback error'))
})
kettanaito commented 2 months ago

Released: v0.29.0 🎉

This has been released in v0.29.0!

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.

mikicho commented 2 months ago

This is really nice! thanks!