1.0.0 • Published 6 years ago

create-custom-error v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
6 years ago

Custom Errors JS

Goals

  • Provide a generalized interface for creating custom errors
  • Custom errors give you a way to respond to exact error events instead of checking up on messages to decide the type of the error.
  • Provide a way to nest errors. So you can always follow them.
  • pass instanceof checks
  • provide code so you can check on it.

The CustomError Class

Creating CustomError classes is done through the createCustomError Factory, which returns an extension of the VError class.

CustomErrors provides you with a convenient factory around VError and a nicer error constructor.

The custom errors pacakge exports two factories: 1. createCustomError(name: String) 2. createHTTPError(name: String, statusCode: number)

createCustomError

The base error factory that extends upon VError, but provides a more convenient constructor.

The call signature(s) is as follows: new CustomError(cause: Error | info: Object, messageArguments: String[]) new CustomError(cause: Error, info: Object, messageArguments: String[]) new CustomError(messageArguments: String[])

Where:

  • cause is an Error, either custom or built-in
  • info is an Object, with any properties
  • messageArguments accepts printf style messages
const err = new Error('Something went wrong...')
const FooError = createCustomError('FooError')
// with error and info
throw new FooError(err, { userId: '123' }, 'Foo: %s', 'bar')
// error only
throw new FooError(err, 'Foo: %s', 'bar')
// info only 
throw new FooError({ userId: '123' }, 'Foo: %s', 'bar')
// messageArguments only 
throw new FooError('Foo: %s', 'bar')

createHTTPError

Is an extension, around createCustmoError, becaue it sets the statusCode property on the error.

The constructor signature is different, but the call signature is the same: createHTTPError(name: String, statusCode: Number)

E.g.:

const UserNotFound = createHTTPError('UserNotFound', 404)