diff --git a/README.md b/README.md index d334b35..efbb26d 100644 --- a/README.md +++ b/README.md @@ -1,148 +1,150 @@ -# http-errors - -This module provides a set of errors based on [standard-http-error](https://www.npmjs.com/package/standard-http-error), reducing the boilerplate of adding error classes for the most common HTTP errors. - -## Status - -[![npm version][npm-image]][npm-url] -[![build status][tests-image]][tests-url] - -## Setup - -Install **@uphold/http-errors** with npm: - -```sh -npm install @uphold/http-errors -``` - -## Errors - -The `HttpError` serves as base error since all other errors extend it, use it to handle errors provided from this library. - -```js -const { BadRequestError, HttpError } = require('@uphold/http-errors'); - -try { - throw new BadRequestError(); -} catch (e) { - console.log(e instanceof HttpError); - // true -} -``` - -Below is the list of all available errors: - -| Name | Code | Default message | -| :---------------------- | :--- | :-------------------- | -| AssertionFailedError | 500 | Internal Server Error | -| BadRequestError | 400 | Bad Request | -| ConflictError | 409 | Conflict | -| ForbiddenError | 403 | Forbidden | -| GoneError | 410 | Gone | -| NotFoundError | 404 | Not Found | -| NotImplementedError | 501 | Not Implemented | -| ServiceUnavailableError | 503 | Service Unavailable | -| TooManyRequestsError | 429 | Too Many Requests | -| UnauthorizedError | 401 | Unauthorized | -| ValidationFailedError | 400 | Validation Failed | - -## Usage - -Import and throw an HTTP error: - -```js -const { ForbiddenError, UnauthorizedError } = require('@uphold/http-errors'); - -function authorize(user, permission) { - if (!user.role) { - throw new UnauthorizedError('User needs to authenticate'); - } - - if (permission === 'admin' && user.role !== 'admin') { - throw new ForbiddenError('Only admins allowed', { role: 'admin' }); - } - - return true; -} -``` - -All errors accept a message and a set of properties as arguments, or both: - -```js -const { BadRequestError } = require('@uphold/http-errors'); - -try { - throw new BadRequestError(); -} catch (e) { - console.log(e); - // { BadRequestError: Bad Request - // at ... - // message: 'Bad Request', name: 'BadRequestError', code: 400 } -} - -try { - throw new BadRequestError('foo'); -} catch (e) { - // { BadRequestError: Bad Request - // at ... - // message: 'foo', name: 'BadRequestError', code: 400 } -} - -try { - throw new BadRequestError({ foo: 'bar' }); -} catch (e) { - console.log(e); - // { BadRequestError: Bad Request - // at ... - // message: 'Bad Request', foo: 'bar', name: 'BadRequestError', code: 400 } -} - -try { - throw new BadRequestError('foo', { bar: 'biz' }); -} catch (e) { - console.log(e); - // { BadRequestError: Bad Request - // at ... - // message: 'foo', bar: 'biz', name: 'BadRequestError', code: 400 } -} -``` - -## Test suite - -Use the `test` script to run the test suite: - -```sh -npm test -``` - -To run the tests on watch mode, use the `test:watch` script: - -```sh -npm run test:watch -``` - -To test and check coverage use the `test:coverage` script: - -```sh -npm run test:coverage -``` - -A full coverage report will be generated on `/coverage` folder. - -## Contributing - -Please create a PR with a description of the changes, its motivation and impacted areas, making sure the build passes. - -## Release process - -The release of a version is automated via the [release](https://github.com/uphold/http-errors/.github/workflows/release.yml) GitHub workflow. -Run it by clicking the "Run workflow" button. - -## License - -MIT - -[npm-image]: https://img.shields.io/npm/v/@uphold/http-errors.svg -[npm-url]: https://www.npmjs.com/package/@uphold/http-errors -[tests-image]: https://github.com/uphold/http-errors/actions/workflows/tests.yaml/badge.svg?branch=master -[tests-url]: https://github.com/uphold/http-errors/actions/workflows/tests.yaml +# http-errors + +This module provides a set of errors based on [standard-http-error](https://www.npmjs.com/package/standard-http-error), reducing the boilerplate of adding error classes for the most common HTTP errors. + +## Status + +[![npm version][npm-image]][npm-url] +[![build status][tests-image]][tests-url] + +## Setup + +Install **@uphold/http-errors** with npm: + +```sh +npm install @uphold/http-errors +``` + +## Errors + +The `HttpError` serves as base error since all other errors extend it, use it to handle errors provided from this library. + +```js +const { BadRequestError, HttpError } = require('@uphold/http-errors'); + +try { + throw new BadRequestError(); +} catch (e) { + console.log(e instanceof HttpError); + // true +} +``` + +Below is the list of all available errors: + +| Name | Code | Default message | +| :---------------------- | :--- | :-------------------- | +| AssertionFailedError | 500 | Assertion Failed | +| BadRequestError | 400 | Bad Request | +| ConflictError | 409 | Conflict | +| ForbiddenError | 403 | Forbidden | +| GoneError | 410 | Gone | +| NotFoundError | 404 | Not Found | +| NotImplementedError | 501 | Not Implemented | +| ServiceUnavailableError | 503 | Service Unavailable | +| TooManyRequestsError | 429 | Too Many Requests | +| UnauthorizedError | 401 | Unauthorized | +| ValidationFailedError | 400 | Validation Failed | + +## Usage + +Import and throw an HTTP error: + +```js +const { ForbiddenError, UnauthorizedError } = require('@uphold/http-errors'); + +function authorize(user, permission) { + if (!user.role) { + throw new UnauthorizedError('User needs to authenticate'); + } + + if (permission === 'admin' && user.role !== 'admin') { + throw new ForbiddenError('Only admins allowed', { role: 'admin' }); + } + + return true; +} +``` + +All errors accept a message and a set of properties as arguments, or both: + +> `AssertionFailedError` and `ValidationFailedError` additionally accept a **single** argument, which is assigned to `error.errors`. This is the form used to carry a `validator.js` violation tree. When two or more arguments are given they follow the `(message, properties)` contract below. + +```js +const { BadRequestError } = require('@uphold/http-errors'); + +try { + throw new BadRequestError(); +} catch (e) { + console.log(e); + // { BadRequestError: Bad Request + // at ... + // message: 'Bad Request', name: 'BadRequestError', code: 400 } +} + +try { + throw new BadRequestError('foo'); +} catch (e) { + // { BadRequestError: Bad Request + // at ... + // message: 'foo', name: 'BadRequestError', code: 400 } +} + +try { + throw new BadRequestError({ foo: 'bar' }); +} catch (e) { + console.log(e); + // { BadRequestError: Bad Request + // at ... + // message: 'Bad Request', foo: 'bar', name: 'BadRequestError', code: 400 } +} + +try { + throw new BadRequestError('foo', { bar: 'biz' }); +} catch (e) { + console.log(e); + // { BadRequestError: Bad Request + // at ... + // message: 'foo', bar: 'biz', name: 'BadRequestError', code: 400 } +} +``` + +## Test suite + +Use the `test` script to run the test suite: + +```sh +npm test +``` + +To run the tests on watch mode, use the `test:watch` script: + +```sh +npm run test:watch +``` + +To test and check coverage use the `test:coverage` script: + +```sh +npm run test:coverage +``` + +A full coverage report will be generated on `/coverage` folder. + +## Contributing + +Please create a PR with a description of the changes, its motivation and impacted areas, making sure the build passes. + +## Release process + +The release of a version is automated via the [release](https://github.com/uphold/http-errors/.github/workflows/release.yaml) GitHub workflow. +Run it by clicking the "Run workflow" button. + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/@uphold/http-errors.svg +[npm-url]: https://www.npmjs.com/package/@uphold/http-errors +[tests-image]: https://github.com/uphold/http-errors/actions/workflows/tests.yaml/badge.svg?branch=master +[tests-url]: https://github.com/uphold/http-errors/actions/workflows/tests.yaml diff --git a/src/errors/assertion-failed-error.js b/src/errors/assertion-failed-error.js index 5f6eab3..d822b74 100644 --- a/src/errors/assertion-failed-error.js +++ b/src/errors/assertion-failed-error.js @@ -1,21 +1,33 @@ -'use strict'; - -/** - * Module dependencies. - */ - -const HttpError = require('./http-error'); - -/** - * Export `AssertionFailedError`. - */ - -module.exports = class AssertionFailedError extends HttpError { - /** - * Constructor. - */ - - constructor(errors) { - super(500, 'Assertion Failed', { errors }); - } -}; +'use strict'; + +/** + * Module dependencies. + */ + +const HttpError = require('./http-error'); + +/** + * Export `AssertionFailedError`. + */ + +module.exports = class AssertionFailedError extends HttpError { + /** + * Constructor. + * + * A single argument is the `errors` payload (typically a validator.js violation tree) and is + * kept for backwards compatibility. Two or more arguments follow the documented + * `(message, properties)` contract shared by every other error in this package: previously the + * second argument was silently discarded, so `new AssertionFailedError('my message', { foo: + * 'bar' })` produced `message === 'Assertion Failed'` and lost `foo`, contradicting the README. + */ + + constructor(...args) { + if (args.length >= 2) { + super(500, ...args); + + return; + } + + super(500, 'Assertion Failed', { errors: args[0] }); + } +}; diff --git a/src/errors/validation-failed-error.js b/src/errors/validation-failed-error.js index ebf07ed..571b741 100644 --- a/src/errors/validation-failed-error.js +++ b/src/errors/validation-failed-error.js @@ -1,21 +1,33 @@ -'use strict'; - -/** - * Module dependencies. - */ - -const HttpError = require('./http-error'); - -/** - * Export "Validation Failed" error. - */ - -module.exports = class ValidationFailedError extends HttpError { - /** - * Constructor. - */ - - constructor(errors) { - super(400, 'Validation Failed', { errors }); - } -}; +'use strict'; + +/** + * Module dependencies. + */ + +const HttpError = require('./http-error'); + +/** + * Export "Validation Failed" error. + */ + +module.exports = class ValidationFailedError extends HttpError { + /** + * Constructor. + * + * A single argument is the `errors` payload (typically a validator.js violation tree) and is + * kept for backwards compatibility. Two or more arguments follow the documented + * `(message, properties)` contract shared by every other error in this package: previously the + * second argument was silently discarded, so `new ValidationFailedError('my message', { foo: + * 'bar' })` produced `message === 'Validation Failed'` and lost `foo`, contradicting the README. + */ + + constructor(...args) { + if (args.length >= 2) { + super(400, ...args); + + return; + } + + super(400, 'Validation Failed', { errors: args[0] }); + } +}; diff --git a/test/errors/assertion-failed-error_test.js b/test/errors/assertion-failed-error_test.js index 6ab30eb..8858b7d 100644 --- a/test/errors/assertion-failed-error_test.js +++ b/test/errors/assertion-failed-error_test.js @@ -1,21 +1,31 @@ -'use strict'; - -/** - * Module dependencies. - */ - -const { AssertionFailedError } = require('../../src'); -const { describe, it } = require('node:test'); -const testHttpError = require('../utils/test-http-error'); - -/** - * Test `Assertion Failed` error. - */ - -describe('AssertionFailedError', () => { - testHttpError(AssertionFailedError, 500, 'Assertion Failed', false); - - it('should set given `errors`', ({ assert }) => { - assert.equal(new AssertionFailedError('foo').errors, 'foo'); - }); -}); +'use strict'; + +/** + * Module dependencies. + */ + +const { AssertionFailedError } = require('../../src'); +const { describe, it } = require('node:test'); +const testHttpError = require('../utils/test-http-error'); + +/** + * Test `Assertion Failed` error. + */ + +describe('AssertionFailedError', () => { + testHttpError(AssertionFailedError, 500, 'Assertion Failed', false); + + it('should set given `errors`', ({ assert }) => { + assert.equal(new AssertionFailedError('foo').errors, 'foo'); + }); + + it('should support the documented `(message, properties)` signature', ({ assert }) => { + // The single-argument form above is reserved for the `errors` payload, so the documented + // message/properties contract only applies when a second argument is supplied. + const error = new AssertionFailedError('my message', { foo: 'bar' }); + + assert.equal(error.message, 'my message'); + assert.equal(error.foo, 'bar'); + assert.equal(error.code, 500); + }); +}); diff --git a/test/errors/validation-failed-error_test.js b/test/errors/validation-failed-error_test.js index 82c5552..0542289 100644 --- a/test/errors/validation-failed-error_test.js +++ b/test/errors/validation-failed-error_test.js @@ -1,21 +1,31 @@ -'use strict'; - -/** - * Module dependencies. - */ - -const { ValidationFailedError } = require('../../src'); -const { describe, test } = require('node:test'); -const testHttpError = require('../utils/test-http-error'); - -/** - * Test `Validation Failed` error. - */ - -describe('ValidationFailedError', () => { - testHttpError(ValidationFailedError, 400, 'Validation Failed', false); - - test('should set given `errors`', ({ assert }) => { - assert.strictEqual(new ValidationFailedError('foo').errors, 'foo'); - }); -}); +'use strict'; + +/** + * Module dependencies. + */ + +const { ValidationFailedError } = require('../../src'); +const { describe, test } = require('node:test'); +const testHttpError = require('../utils/test-http-error'); + +/** + * Test `Validation Failed` error. + */ + +describe('ValidationFailedError', () => { + testHttpError(ValidationFailedError, 400, 'Validation Failed', false); + + test('should set given `errors`', ({ assert }) => { + assert.strictEqual(new ValidationFailedError('foo').errors, 'foo'); + }); + + test('should support the documented `(message, properties)` signature', ({ assert }) => { + // The single-argument form above is reserved for the `errors` payload, so the documented + // message/properties contract only applies when a second argument is supplied. + const error = new ValidationFailedError('my message', { foo: 'bar' }); + + assert.equal(error.message, 'my message'); + assert.equal(error.foo, 'bar'); + assert.equal(error.code, 400); + }); +});