error-system icon indicating copy to clipboard operation
error-system copied to clipboard

Extend documentation is incorrect; both functions mutate Error

Open samliebow opened this issue 7 years ago • 0 comments

The provided code sample for errorSystem.extend (copied at bottom) will crash if run, with TypeError: RequestError.NotFound is not a constructor. Less obviously, new RequestError creates an instance of Error, not an instance of the new error.

This is because extend mutates the function it's given - in this case Error - by adding the new error constructor as a property, then returns the mutated function. To access the new constructor, you would need to use var RequestError = errorSystem.extend(<see below>).RequestError, or var { RequestError } = errorSystem.extend(<see below>).

errorSystem.createError mutates Error but returns the new error constructor. This is still undesirable behavior, since most people won't want to mutate a native function without at least being aware they're doing so.

var errorSystem = require('error-system')
var RequestError = errorSystem.extend(Error, [{
  name: 'RequestError',
  message: 'Code: {0} (url: {1})',
  errors: [
    {
      name: 'NotFound',
      message: 'Code: 404 (url: {0})'
    }
  ]
}])
var request = require('request')

var url = 'https://github.com/notfound11'
request(url, function (error, response) {
  if (error === null && response.statusCode !== 200) {
    if (response.statusCode === 404) {
      error = new RequestError.NotFound(url)
    } else if (response.statusCode !== 200) {
      error = new RequestError(response.statusCode, url)
    }
  }

  if (error !== null) {
    // ErrorRequestErrorNotFound: Code: 404 (url: https://github.com/notfound11)
    console.error(error.stack.split('\n')[0])
  }
})

samliebow avatar Jan 11 '19 20:01 samliebow