create-boom-error
Version:
Simply create sub-classed Boom errors for Hapi applications.
67 lines (40 loc) • 1.88 kB
Markdown
A simple Node.js library for easily creating classed Boom errors in Hapi applications.
`npm install create-boom-error`
Creates a Boom error.
- `name` - The name of the error.
- `statusCode` - the integer status code of the Boom error
- `message` - an optional string or function which returns a string
- `code` - an optional machine-keyable error status string
```js
const { createBoomError } = require('create-boom-error');
const MyError = createBoomError('MyError', 404, 'simple message', 'not_found');
const err = new MyError();
// err is an instance of MyError making it easy to check in tests
err instanceof MyError // => true
// err.code will match the code argument passed in
err.code // => 'not_found'
```
Note that if the optional `code` argument is *NOT* passed in then the `.code` field attached to the error will default to a decamelized, snake case version of the `name`. For example:
```js
const MyError = createBoomError('MyError', 404, 'simple message');
const err = new MyError();
// err is an instance of MyError making it easy to check in tests
err instanceof MyError // => true
// err.code will return the name argument decamelized and in snake case
err.code // => 'my_error'
```
```js
const MyError = createBoomError('MyError', 404, (num) => `You must have more than ${num} coins.`);
const err = new MyError(4);
// err now has the dynamic message
err.message // => 'You must have more than 4 coins.'
```
`npm run test`