mswjs / interceptors

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

Handle errors in the interceptor handler #437

Closed mikicho closed 11 months ago

mikicho commented 11 months ago

Following this comment.

Problem: this line throws when an error occurs in the handler. This prevents the user from handling errors with error listener in the request, which causes this test to fail.

I think it's because we currently don't catch the promise, we only handle the then case.

kettanaito commented 11 months ago

Hi. Have you tried using Response.error() instead of throwing in the request listener?

until() works as try/catch so exceptions in its closure will also propagate to the .then() callback as result.error.

mikicho commented 11 months ago

Hi. Have you tried using Response.error() instead of throwing in the request listener?

Yes, it converts the error to a generic Network error, which is not what we are after.

until() works as try/catch so exceptions in its closure will also propagate to the .then() callback as result.error.

Interesting, this is not what I see, the code never gets to the then clause, I'll try to reproduce it in a small script without Nock's noise.

mikicho commented 11 months ago

Update: it seems like it's working as expected when I isolated the scenario in a small script. I'll keep updating my findings and close this ticket if needed.

mikicho commented 11 months ago

My mistake. For reference, if you use a promise, reject it instead of throw an error:

interceptor.on('request', function ({ request, requestId }) {
  return new Promise((resolve, reject) => {
     throw error; // not working
     reject(error) // good
  })
});