mswjs / interceptors

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

Don't supress interceptors errors #452

Closed mikicho closed 1 year ago

mikicho commented 1 year ago

Currently, we suppress all errors for specific types, which prevent the user to throw these error within the interceptors handler:

const { ClientRequestInterceptor } = require('@mswjs/interceptors/ClientRequest')
const http = require('http');
const { inherits } = require('util');

const interceptor = new ClientRequestInterceptor({
  name: 'my-interceptor',
})
interceptor.apply();
interceptor.on('request', ({request}) => {
  throw new NetConnectNotAllowedError('example.test', '/')
});

http.get('http://nowhere.com/', res => {
  res.on('data', () => {})
  res.on('end', () => {
    console.log(1) 
  })
})
.on('error', e => {
  console.log('custom error') // never get called!!!
})

function NetConnectNotAllowedError(host, path) {
  Error.call(this)

  this.name = 'NetConnectNotAllowedError'
  this.code = 'ENETUNREACH'
  this.message = `Nock: Disallowed net connect for "${host}${path}"`

  Error.captureStackTrace(this, this.constructor)
}

inherits(NetConnectNotAllowedError, Error)

As I see it, we can do one of two things:

  1. have a flag that indicates that the error is from the user and shouldn't be suppressed.
  2. Set the default resourceSource to pass or to undefined
kettanaito commented 1 year ago

Oh, I see. Since the thrown errors result in error being emitted, and we have the suppressing logic in there, those user-defined errors never get emitted.

I think this should be fairly easy to fix by introducing a state that tells the interceptor that we are past socket connection phase, and it should no longer suppress the errors. This is a bit naive and relies on the suppressed errors originating from the connection alone but that's also the only use case we have for those suppressed errors as of now.

mikicho commented 1 year ago

Great. I can open a PR if needed.

kettanaito commented 1 year ago

That would be much appreciated! Let's iterate on it together.

kettanaito commented 1 year ago

Released: v0.25.7 🎉

This has been released in v0.25.7!

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.