pax_global_header00006660000000000000000000000064141443146320014514gustar00rootroot0000000000000052 comment=a3010a313e33bf0bd9b12158f0d63c0d669519bc http-errors-1.8.1/000077500000000000000000000000001414431463200140145ustar00rootroot00000000000000http-errors-1.8.1/.eslintignore000066400000000000000000000000261414431463200165150ustar00rootroot00000000000000coverage node_modules http-errors-1.8.1/.eslintrc.yml000066400000000000000000000002321414431463200164350ustar00rootroot00000000000000root: true extends: - standard - plugin:markdown/recommended plugins: - markdown overrides: - files: '**/*.md' processor: 'markdown/markdown' http-errors-1.8.1/.github/000077500000000000000000000000001414431463200153545ustar00rootroot00000000000000http-errors-1.8.1/.github/workflows/000077500000000000000000000000001414431463200174115ustar00rootroot00000000000000http-errors-1.8.1/.github/workflows/ci.yml000066400000000000000000000123731414431463200205350ustar00rootroot00000000000000name: ci on: - pull_request - push jobs: test: runs-on: ubuntu-18.04 strategy: matrix: name: - Node.js 0.6 - Node.js 0.8 - Node.js 0.10 - Node.js 0.12 - io.js 1.x - io.js 2.x - io.js 3.x - Node.js 4.x - Node.js 5.x - Node.js 6.x - Node.js 7.x - Node.js 8.x - Node.js 9.x - Node.js 10.x - Node.js 11.x - Node.js 12.x - Node.js 13.x - Node.js 14.x - Node.js 15.x - Node.js 16.x - Node.js 17.x include: - name: Node.js 0.6 node-version: "0.6" npm-i: mocha@1.21.5 npm-rm: nyc - name: Node.js 0.8 node-version: "0.8" npm-i: mocha@2.5.3 npm-rm: nyc - name: Node.js 0.10 node-version: "0.10" npm-i: mocha@3.5.3 nyc@10.3.2 - name: Node.js 0.12 node-version: "0.12" npm-i: mocha@3.5.3 nyc@10.3.2 - name: io.js 1.x node-version: "1.8" npm-i: mocha@3.5.3 nyc@10.3.2 - name: io.js 2.x node-version: "2.5" npm-i: mocha@3.5.3 nyc@10.3.2 - name: io.js 3.x node-version: "3.3" npm-i: mocha@3.5.3 nyc@10.3.2 - name: Node.js 4.x node-version: "4.9" npm-i: mocha@5.2.0 nyc@11.9.0 - name: Node.js 5.x node-version: "5.12" npm-i: mocha@5.2.0 nyc@11.9.0 - name: Node.js 6.x node-version: "6.17" npm-i: mocha@6.2.2 nyc@14.1.1 - name: Node.js 7.x node-version: "7.10" npm-i: mocha@6.2.2 nyc@14.1.1 - name: Node.js 8.x node-version: "8.17" npm-i: mocha@7.2.0 - name: Node.js 9.x node-version: "9.11" npm-i: mocha@7.2.0 - name: Node.js 10.x node-version: "10.24" npm-i: mocha@8.4.0 - name: Node.js 11.x node-version: "11.15" npm-i: mocha@8.4.0 - name: Node.js 12.x node-version: "12.22" - name: Node.js 13.x node-version: "13.14" - name: Node.js 14.x node-version: "14.18" - name: Node.js 15.x node-version: "15.14" - name: Node.js 16.x node-version: "16.13" - name: Node.js 17.x node-version: "17.1" steps: - uses: actions/checkout@v2 - name: Install Node.js ${{ matrix.node-version }} shell: bash -eo pipefail -l {0} run: | if [[ "${{ matrix.node-version }}" == 0.6* ]]; then sudo apt-get install g++-4.8 gcc-4.8 libssl1.0-dev export CC=/usr/bin/gcc-4.8 export CXX=/usr/bin/g++-4.8 fi nvm install --default ${{ matrix.node-version }} if [[ "${{ matrix.node-version }}" == 0.* && "$(cut -d. -f2 <<< "${{ matrix.node-version }}")" -lt 10 ]]; then nvm install --alias=npm 0.10 nvm use ${{ matrix.node-version }} if [[ "$(npm -v)" == 1.1.* ]]; then nvm exec npm npm install -g npm@1.1 ln -fs "$(which npm)" "$(dirname "$(nvm which npm)")/npm" else sed -i '1s;^.*$;'"$(printf '#!%q' "$(nvm which npm)")"';' "$(readlink -f "$(which npm)")" fi npm config set strict-ssl false fi dirname "$(nvm which ${{ matrix.node-version }})" >> "$GITHUB_PATH" - name: Configure npm run: npm config set shrinkwrap false - name: Remove npm module(s) ${{ matrix.npm-rm }} run: npm rm --silent --save-dev ${{ matrix.npm-rm }} if: matrix.npm-rm != '' - name: Install npm module(s) ${{ matrix.npm-i }} run: npm install --save-dev ${{ matrix.npm-i }} if: matrix.npm-i != '' - name: Setup Node.js version-specific dependencies shell: bash run: | # eslint for linting # - remove on Node.js < 10 if [[ "$(cut -d. -f1 <<< "${{ matrix.node-version }}")" -lt 10 ]]; then node -pe 'Object.keys(require("./package").devDependencies).join("\n")' | \ grep -E '^eslint(-|$)' | \ sort -r | \ xargs -n1 npm rm --silent --save-dev fi - name: Install Node.js dependencies run: npm install - name: List environment id: list_env shell: bash run: | echo "node@$(node -v)" echo "npm@$(npm -v)" npm -s ls ||: (npm -s ls --depth=0 ||:) | awk -F'[ @]' 'NR>1 && $2 { print "::set-output name=" $2 "::" $3 }' - name: Run tests shell: bash run: | if npm -ps ls nyc | grep -q nyc; then npm run test-ci else npm test fi - name: Lint code if: steps.list_env.outputs.eslint != '' run: npm run lint - name: Collect code coverage uses: coverallsapp/github-action@master if: steps.list_env.outputs.nyc != '' with: github-token: ${{ secrets.GITHUB_TOKEN }} flag-name: run-${{ matrix.test_number }} parallel: true coverage: needs: test runs-on: ubuntu-latest steps: - name: Upload code coverage uses: coverallsapp/github-action@master with: github-token: ${{ secrets.github_token }} parallel-finished: true http-errors-1.8.1/.gitignore000066400000000000000000000001141414431463200160000ustar00rootroot00000000000000 .DS_Store* *.log *.gz .nyc_output node_modules coverage package-lock.json http-errors-1.8.1/HISTORY.md000066400000000000000000000065321414431463200155050ustar00rootroot000000000000002021-11-14 / 1.8.1 ================== * deps: toidentifier@1.0.1 2020-06-29 / 1.8.0 ================== * Add `isHttpError` export to determine if value is an HTTP error * deps: setprototypeof@1.2.0 2019-06-24 / 1.7.3 ================== * deps: inherits@2.0.4 2019-02-18 / 1.7.2 ================== * deps: setprototypeof@1.1.1 2018-09-08 / 1.7.1 ================== * Fix error creating objects in some environments 2018-07-30 / 1.7.0 ================== * Set constructor name when possible * Use `toidentifier` module to make class names * deps: statuses@'>= 1.5.0 < 2' 2018-03-29 / 1.6.3 ================== * deps: depd@~1.1.2 - perf: remove argument reassignment * deps: setprototypeof@1.1.0 * deps: statuses@'>= 1.4.0 < 2' 2017-08-04 / 1.6.2 ================== * deps: depd@1.1.1 - Remove unnecessary `Buffer` loading 2017-02-20 / 1.6.1 ================== * deps: setprototypeof@1.0.3 - Fix shim for old browsers 2017-02-14 / 1.6.0 ================== * Accept custom 4xx and 5xx status codes in factory * Add deprecation message to `"I'mateapot"` export * Deprecate passing status code as anything except first argument in factory * Deprecate using non-error status codes * Make `message` property enumerable for `HttpError`s 2016-11-16 / 1.5.1 ================== * deps: inherits@2.0.3 - Fix issue loading in browser * deps: setprototypeof@1.0.2 * deps: statuses@'>= 1.3.1 < 2' 2016-05-18 / 1.5.0 ================== * Support new code `421 Misdirected Request` * Use `setprototypeof` module to replace `__proto__` setting * deps: statuses@'>= 1.3.0 < 2' - Add `421 Misdirected Request` - perf: enable strict mode * perf: enable strict mode 2016-01-28 / 1.4.0 ================== * Add `HttpError` export, for `err instanceof createError.HttpError` * deps: inherits@2.0.1 * deps: statuses@'>= 1.2.1 < 2' - Fix message for status 451 - Remove incorrect nginx status code 2015-02-02 / 1.3.1 ================== * Fix regression where status can be overwritten in `createError` `props` 2015-02-01 / 1.3.0 ================== * Construct errors using defined constructors from `createError` * Fix error names that are not identifiers - `createError["I'mateapot"]` is now `createError.ImATeapot` * Set a meaningful `name` property on constructed errors 2014-12-09 / 1.2.8 ================== * Fix stack trace from exported function * Remove `arguments.callee` usage 2014-10-14 / 1.2.7 ================== * Remove duplicate line 2014-10-02 / 1.2.6 ================== * Fix `expose` to be `true` for `ClientError` constructor 2014-09-28 / 1.2.5 ================== * deps: statuses@1 2014-09-21 / 1.2.4 ================== * Fix dependency version to work with old `npm`s 2014-09-21 / 1.2.3 ================== * deps: statuses@~1.1.0 2014-09-21 / 1.2.2 ================== * Fix publish error 2014-09-21 / 1.2.1 ================== * Support Node.js 0.6 * Use `inherits` instead of `util` 2014-09-09 / 1.2.0 ================== * Fix the way inheriting functions * Support `expose` being provided in properties argument 2014-09-08 / 1.1.0 ================== * Default status to 500 * Support provided `error` to extend 2014-09-08 / 1.0.1 ================== * Fix accepting string message 2014-09-08 / 1.0.0 ================== * Initial release http-errors-1.8.1/LICENSE000066400000000000000000000022201414431463200150150ustar00rootroot00000000000000 The MIT License (MIT) Copyright (c) 2014 Jonathan Ong me@jongleberry.com Copyright (c) 2016 Douglas Christopher Wilson doug@somethingdoug.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. http-errors-1.8.1/README.md000066400000000000000000000135071414431463200153010ustar00rootroot00000000000000# http-errors [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][node-url] [![Node.js Version][node-image]][node-url] [![Build Status][ci-image]][ci-url] [![Test Coverage][coveralls-image]][coveralls-url] Create HTTP errors for Express, Koa, Connect, etc. with ease. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```bash $ npm install http-errors ``` ## Example ```js var createError = require('http-errors') var express = require('express') var app = express() app.use(function (req, res, next) { if (!req.user) return next(createError(401, 'Please login to view this page.')) next() }) ``` ## API This is the current API, currently extracted from Koa and subject to change. ### Error Properties - `expose` - can be used to signal if `message` should be sent to the client, defaulting to `false` when `status` >= 500 - `headers` - can be an object of header names to values to be sent to the client, defaulting to `undefined`. When defined, the key names should all be lower-cased - `message` - the traditional error message, which should be kept short and all single line - `status` - the status code of the error, mirroring `statusCode` for general compatibility - `statusCode` - the status code of the error, defaulting to `500` ### createError([status], [message], [properties]) Create a new error object with the given message `msg`. The error object inherits from `createError.HttpError`. ```js var err = createError(404, 'This video does not exist!') ``` - `status: 500` - the status code as a number - `message` - the message of the error, defaulting to node's text for that status code. - `properties` - custom properties to attach to the object ### createError([status], [error], [properties]) Extend the given `error` object with `createError.HttpError` properties. This will not alter the inheritance of the given `error` object, and the modified `error` object is the return value. ```js fs.readFile('foo.txt', function (err, buf) { if (err) { if (err.code === 'ENOENT') { var httpError = createError(404, err, { expose: false }) } else { var httpError = createError(500, err) } } }) ``` - `status` - the status code as a number - `error` - the error object to extend - `properties` - custom properties to attach to the object ### createError.isHttpError(val) Determine if the provided `val` is an `HttpError`. This will return `true` if the error inherits from the `HttpError` constructor of this module or matches the "duck type" for an error this module creates. All outputs from the `createError` factory will return `true` for this function, including if an non-`HttpError` was passed into the factory. ### new createError\[code || name\](\[msg]\)) Create a new error object with the given message `msg`. The error object inherits from `createError.HttpError`. ```js var err = new createError.NotFound() ``` - `code` - the status code as a number - `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. #### List of all constructors |Status Code|Constructor Name | |-----------|-----------------------------| |400 |BadRequest | |401 |Unauthorized | |402 |PaymentRequired | |403 |Forbidden | |404 |NotFound | |405 |MethodNotAllowed | |406 |NotAcceptable | |407 |ProxyAuthenticationRequired | |408 |RequestTimeout | |409 |Conflict | |410 |Gone | |411 |LengthRequired | |412 |PreconditionFailed | |413 |PayloadTooLarge | |414 |URITooLong | |415 |UnsupportedMediaType | |416 |RangeNotSatisfiable | |417 |ExpectationFailed | |418 |ImATeapot | |421 |MisdirectedRequest | |422 |UnprocessableEntity | |423 |Locked | |424 |FailedDependency | |425 |UnorderedCollection | |426 |UpgradeRequired | |428 |PreconditionRequired | |429 |TooManyRequests | |431 |RequestHeaderFieldsTooLarge | |451 |UnavailableForLegalReasons | |500 |InternalServerError | |501 |NotImplemented | |502 |BadGateway | |503 |ServiceUnavailable | |504 |GatewayTimeout | |505 |HTTPVersionNotSupported | |506 |VariantAlsoNegotiates | |507 |InsufficientStorage | |508 |LoopDetected | |509 |BandwidthLimitExceeded | |510 |NotExtended | |511 |NetworkAuthenticationRequired| ## License [MIT](LICENSE) [ci-image]: https://badgen.net/github/checks/jshttp/http-errors/master?label=ci [ci-url]: https://github.com/jshttp/http-errors/actions?query=workflow%3Aci [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/http-errors/master [coveralls-url]: https://coveralls.io/r/jshttp/http-errors?branch=master [node-image]: https://badgen.net/npm/node/http-errors [node-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/http-errors [npm-url]: https://npmjs.org/package/http-errors [npm-version-image]: https://badgen.net/npm/v/http-errors [travis-image]: https://badgen.net/travis/jshttp/http-errors/master [travis-url]: https://travis-ci.org/jshttp/http-errors http-errors-1.8.1/index.js000066400000000000000000000145711414431463200154710ustar00rootroot00000000000000/*! * http-errors * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2016 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module dependencies. * @private */ var deprecate = require('depd')('http-errors') var setPrototypeOf = require('setprototypeof') var statuses = require('statuses') var inherits = require('inherits') var toIdentifier = require('toidentifier') /** * Module exports. * @public */ module.exports = createError module.exports.HttpError = createHttpErrorConstructor() module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError) // Populate exports for all constructors populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) /** * Get the code class of a status code. * @private */ function codeClass (status) { return Number(String(status).charAt(0) + '00') } /** * Create a new HTTP Error. * * @returns {Error} * @public */ function createError () { // so much arity going on ~_~ var err var msg var status = 500 var props = {} for (var i = 0; i < arguments.length; i++) { var arg = arguments[i] if (arg instanceof Error) { err = arg status = err.status || err.statusCode || status continue } switch (typeof arg) { case 'string': msg = arg break case 'number': status = arg if (i !== 0) { deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') } break case 'object': props = arg break } } if (typeof status === 'number' && (status < 400 || status >= 600)) { deprecate('non-error status code; use only 4xx or 5xx status codes') } if (typeof status !== 'number' || (!statuses[status] && (status < 400 || status >= 600))) { status = 500 } // constructor var HttpError = createError[status] || createError[codeClass(status)] if (!err) { // create error err = HttpError ? new HttpError(msg) : new Error(msg || statuses[status]) Error.captureStackTrace(err, createError) } if (!HttpError || !(err instanceof HttpError) || err.status !== status) { // add properties to generic error err.expose = status < 500 err.status = err.statusCode = status } for (var key in props) { if (key !== 'status' && key !== 'statusCode') { err[key] = props[key] } } return err } /** * Create HTTP error abstract base class. * @private */ function createHttpErrorConstructor () { function HttpError () { throw new TypeError('cannot construct abstract class') } inherits(HttpError, Error) return HttpError } /** * Create a constructor for a client error. * @private */ function createClientErrorConstructor (HttpError, name, code) { var className = toClassName(name) function ClientError (message) { // create the error object var msg = message != null ? message : statuses[code] var err = new Error(msg) // capture a stack trace to the construction point Error.captureStackTrace(err, ClientError) // adjust the [[Prototype]] setPrototypeOf(err, ClientError.prototype) // redefine the error message Object.defineProperty(err, 'message', { enumerable: true, configurable: true, value: msg, writable: true }) // redefine the error name Object.defineProperty(err, 'name', { enumerable: false, configurable: true, value: className, writable: true }) return err } inherits(ClientError, HttpError) nameFunc(ClientError, className) ClientError.prototype.status = code ClientError.prototype.statusCode = code ClientError.prototype.expose = true return ClientError } /** * Create function to test is a value is a HttpError. * @private */ function createIsHttpErrorFunction (HttpError) { return function isHttpError (val) { if (!val || typeof val !== 'object') { return false } if (val instanceof HttpError) { return true } return val instanceof Error && typeof val.expose === 'boolean' && typeof val.statusCode === 'number' && val.status === val.statusCode } } /** * Create a constructor for a server error. * @private */ function createServerErrorConstructor (HttpError, name, code) { var className = toClassName(name) function ServerError (message) { // create the error object var msg = message != null ? message : statuses[code] var err = new Error(msg) // capture a stack trace to the construction point Error.captureStackTrace(err, ServerError) // adjust the [[Prototype]] setPrototypeOf(err, ServerError.prototype) // redefine the error message Object.defineProperty(err, 'message', { enumerable: true, configurable: true, value: msg, writable: true }) // redefine the error name Object.defineProperty(err, 'name', { enumerable: false, configurable: true, value: className, writable: true }) return err } inherits(ServerError, HttpError) nameFunc(ServerError, className) ServerError.prototype.status = code ServerError.prototype.statusCode = code ServerError.prototype.expose = false return ServerError } /** * Set the name of a function, if possible. * @private */ function nameFunc (func, name) { var desc = Object.getOwnPropertyDescriptor(func, 'name') if (desc && desc.configurable) { desc.value = name Object.defineProperty(func, 'name', desc) } } /** * Populate the exports object with constructors for every error class. * @private */ function populateConstructorExports (exports, codes, HttpError) { codes.forEach(function forEachCode (code) { var CodeError var name = toIdentifier(statuses[code]) switch (codeClass(code)) { case 400: CodeError = createClientErrorConstructor(HttpError, name, code) break case 500: CodeError = createServerErrorConstructor(HttpError, name, code) break } if (CodeError) { // export the constructor exports[code] = CodeError exports[name] = CodeError } }) // backwards-compatibility exports["I'mateapot"] = deprecate.function(exports.ImATeapot, '"I\'mateapot"; use "ImATeapot" instead') } /** * Get a class name from a name identifier. * @private */ function toClassName (name) { return name.substr(-5) !== 'Error' ? name + 'Error' : name } http-errors-1.8.1/package.json000066400000000000000000000023421414431463200163030ustar00rootroot00000000000000{ "name": "http-errors", "description": "Create HTTP error objects", "version": "1.8.1", "author": "Jonathan Ong (http://jongleberry.com)", "contributors": [ "Alan Plum ", "Douglas Christopher Wilson " ], "license": "MIT", "repository": "jshttp/http-errors", "dependencies": { "depd": "~1.1.2", "inherits": "2.0.4", "setprototypeof": "1.2.0", "statuses": ">= 1.5.0 < 2", "toidentifier": "1.0.1" }, "devDependencies": { "eslint": "7.32.0", "eslint-config-standard": "14.1.1", "eslint-plugin-import": "2.25.3", "eslint-plugin-markdown": "2.2.1", "eslint-plugin-node": "11.1.0", "eslint-plugin-promise": "5.1.1", "eslint-plugin-standard": "4.1.0", "mocha": "9.1.3", "nyc": "15.1.0" }, "engines": { "node": ">= 0.6" }, "scripts": { "lint": "eslint . && node ./scripts/lint-readme-list.js", "test": "mocha --reporter spec --bail", "test-ci": "nyc --reporter=lcov --reporter=text npm test", "test-cov": "nyc --reporter=html --reporter=text npm test" }, "keywords": [ "http", "error" ], "files": [ "index.js", "HISTORY.md", "LICENSE", "README.md" ] } http-errors-1.8.1/scripts/000077500000000000000000000000001414431463200155035ustar00rootroot00000000000000http-errors-1.8.1/scripts/lint-readme-list.js000066400000000000000000000013101414431463200212060ustar00rootroot00000000000000var assert = require('assert') var createError = require('..') var fs = require('fs') var path = require('path') var util = require('util') var README_PATH = path.join(__dirname, '..', 'README.md') var README_CONTENTS = fs.readFileSync(README_PATH, 'utf-8') Object.keys(createError).forEach(function (key) { if (!isNaN(key)) { return } var constructor = createError[key] var statusCode = constructor.prototype.statusCode if (createError[statusCode] !== constructor) { return } var regexp = new RegExp(util.format('^\\|%d\\s*\\|%s\\s*\\|$', statusCode, key), 'm') assert.ok(regexp.test(README_CONTENTS), util.format('README constructor list contains %d %s', statusCode, key)) }) http-errors-1.8.1/test/000077500000000000000000000000001414431463200147735ustar00rootroot00000000000000http-errors-1.8.1/test/.eslintrc.yml000066400000000000000000000000231414431463200174120ustar00rootroot00000000000000env: mocha: true http-errors-1.8.1/test/test.js000066400000000000000000000315521414431463200163160ustar00rootroot00000000000000 process.env.NO_DEPRECATION = 'http-errors' var assert = require('assert') var util = require('util') var createError = require('..') describe('createError(status)', function () { it('should create error object', function () { assert.ok(util.isError(createError(500))) // eslint-disable-line node/no-deprecated-api }) describe('when status 300', function () { before(function () { this.error = createError(300) }) it('should have "message" property of "Multiple Choices"', function () { assert.strictEqual(this.error.message, 'Multiple Choices') }) it('should have "name" property of "Error"', function () { assert.strictEqual(this.error.name, 'Error') }) it('should have "status" property of 300', function () { assert.strictEqual(this.error.status, 300) }) it('should have "statusCode" property of 300', function () { assert.strictEqual(this.error.statusCode, 300) }) }) describe('when status 404', function () { before(function () { this.error = createError(404) }) it('should have "message" property of "Not Found"', function () { assert.strictEqual(this.error.message, 'Not Found') }) it('should have "name" property of "NotFoundError"', function () { assert.strictEqual(this.error.name, 'NotFoundError') }) it('should have "status" property of 404', function () { assert.strictEqual(this.error.status, 404) }) it('should have "statusCode" property of 404', function () { assert.strictEqual(this.error.statusCode, 404) }) }) describe('when status unknown 4xx', function () { before(function () { this.error = createError(499) }) it('should have "message" property of "Bad Request"', function () { assert.strictEqual(this.error.message, 'Bad Request') }) it('should have "name" property of "BadRequestError"', function () { assert.strictEqual(this.error.name, 'BadRequestError') }) it('should have "status" property with code', function () { assert.strictEqual(this.error.status, 499) }) it('should have "statusCode" property with code', function () { assert.strictEqual(this.error.statusCode, 499) }) }) describe('when status unknown 5xx', function () { before(function () { this.error = createError(599) }) it('should have "message" property of "Internal Server Error"', function () { assert.strictEqual(this.error.message, 'Internal Server Error') }) it('should have "name" property of "InternalServerError"', function () { assert.strictEqual(this.error.name, 'InternalServerError') }) it('should have "status" property with code', function () { assert.strictEqual(this.error.status, 599) }) it('should have "statusCode" property with code', function () { assert.strictEqual(this.error.statusCode, 599) }) }) }) describe('createError(status, message)', function () { before(function () { this.error = createError(404, 'missing') }) it('should create error object', function () { assert.ok(util.isError(this.error)) // eslint-disable-line node/no-deprecated-api }) it('should have "message" property with message', function () { assert.strictEqual(this.error.message, 'missing') }) it('should have "status" property with status', function () { assert.strictEqual(this.error.status, 404) }) it('should have "statusCode" property with status', function () { assert.strictEqual(this.error.statusCode, 404) }) }) describe('createError.isHttpError(val)', function () { describe('when val is undefined', function () { it('should return false', function () { assert.strictEqual(createError.isHttpError(undefined), false) }) }) describe('when val is null', function () { it('should return false', function () { assert.strictEqual(createError.isHttpError(null), false) }) }) describe('when val is a number', function () { it('should return false', function () { assert.strictEqual(createError.isHttpError(42), false) }) }) describe('when val is a string', function () { it('should return false', function () { assert.strictEqual(createError.isHttpError('foobar'), false) }) }) describe('when val is an empty object', function () { it('should return false', function () { assert.strictEqual(createError.isHttpError({}), false) }) }) describe('when val is a plain Error', function () { it('should return false', function () { assert.strictEqual(createError.isHttpError(new Error()), false) }) }) describe('when val is an instance of HttpError', function () { it('should return true', function () { var err = createError(500) assert.ok(err instanceof createError.HttpError) assert.strictEqual(createError.isHttpError(err), true) }) }) describe('when val is an Error passed to createError', function () { it('should return true', function () { var err = createError(500, new Error()) assert.ok(!(err instanceof createError.HttpError)) assert.strictEqual(createError.isHttpError(err), true) }) }) }) describe('HTTP Errors', function () { it('createError(status, props)', function () { var err = createError(404, { id: 1 }) assert.strictEqual(err.name, 'NotFoundError') assert.strictEqual(err.message, 'Not Found') assert.strictEqual(err.status, 404) assert.strictEqual(err.statusCode, 404) assert.strictEqual(err.id, 1) }) it('createError(status, props) with status prop', function () { var err = createError(404, { id: 1, status: 500 }) assert.strictEqual(err.name, 'NotFoundError') assert.strictEqual(err.message, 'Not Found') assert.strictEqual(err.status, 404) assert.strictEqual(err.statusCode, 404) assert.strictEqual(err.id, 1) }) it('createError(status, props) with statusCode prop', function () { var err = createError(404, { id: 1, statusCode: 500 }) assert.strictEqual(err.name, 'NotFoundError') assert.strictEqual(err.message, 'Not Found') assert.strictEqual(err.status, 404) assert.strictEqual(err.statusCode, 404) assert.strictEqual(err.id, 1) }) it('createError(props)', function () { var err = createError({ id: 1 }) assert.strictEqual(err.name, 'InternalServerError') assert.strictEqual(err.message, 'Internal Server Error') assert.strictEqual(err.status, 500) assert.strictEqual(err.statusCode, 500) assert.strictEqual(err.id, 1) }) it('createError(msg, status)', function () { var err = createError('LOL', 404) assert.strictEqual(err.name, 'NotFoundError') assert.strictEqual(err.message, 'LOL') assert.strictEqual(err.status, 404) assert.strictEqual(err.statusCode, 404) }) it('createError(msg)', function () { var err = createError('LOL') assert.strictEqual(err.name, 'InternalServerError') assert.strictEqual(err.message, 'LOL') assert.strictEqual(err.status, 500) assert.strictEqual(err.statusCode, 500) }) it('createError(msg, props)', function () { var err = createError('LOL', { id: 1 }) assert.strictEqual(err.name, 'InternalServerError') assert.strictEqual(err.message, 'LOL') assert.strictEqual(err.status, 500) assert.strictEqual(err.statusCode, 500) assert.strictEqual(err.id, 1) }) it('createError(err)', function () { var _err = new Error('LOL') _err.status = 404 var err = createError(_err) assert.strictEqual(err, _err) assert.strictEqual(err.name, 'Error') assert.strictEqual(err.message, 'LOL') assert.strictEqual(err.status, 404) assert.strictEqual(err.statusCode, 404) assert.strictEqual(err.expose, true) _err = new Error('LOL') err = createError(_err) assert.strictEqual(err, _err) assert.strictEqual(err.name, 'Error') assert.strictEqual(err.message, 'LOL') assert.strictEqual(err.status, 500) assert.strictEqual(err.statusCode, 500) assert.strictEqual(err.expose, false) err = createError(null) assert.notStrictEqual(err, null) assert.strictEqual(err.name, 'InternalServerError') assert.strictEqual(err.message, 'Internal Server Error') assert.strictEqual(err.status, 500) assert.strictEqual(err.statusCode, 500) assert.strictEqual(err.expose, false) }) it('createError(err) with invalid err.status', function () { var _err = new Error('Connection refused') _err.status = -1 var err = createError(_err) assert.strictEqual(err, _err) assert.strictEqual(err.name, 'Error') assert.strictEqual(err.message, 'Connection refused') assert.strictEqual(err.status, 500) assert.strictEqual(err.statusCode, 500) assert.strictEqual(err.expose, false) }) it('createError(err, props)', function () { var _err = new Error('LOL') _err.status = 404 var err = createError(_err, { id: 1 }) assert.strictEqual(err.name, 'Error') assert.strictEqual(err.message, 'LOL') assert.strictEqual(err.status, 404) assert.strictEqual(err.statusCode, 404) assert.strictEqual(err.id, 1) assert.strictEqual(err.expose, true) }) it('createError(status, err, props)', function () { var _err = new Error('LOL') var err = createError(404, _err, { id: 1 }) assert.strictEqual(err, _err) assert.strictEqual(err.name, 'Error') assert.strictEqual(err.message, 'LOL') assert.strictEqual(err.status, 404) assert.strictEqual(err.statusCode, 404) assert.strictEqual(err.id, 1) }) it('createError(status, msg, props)', function () { var err = createError(404, 'LOL', { id: 1 }) assert.strictEqual(err.name, 'NotFoundError') assert.strictEqual(err.message, 'LOL') assert.strictEqual(err.status, 404) assert.strictEqual(err.statusCode, 404) assert.strictEqual(err.id, 1) }) it('createError(status, msg, { expose: false })', function () { var err = createError(404, 'LOL', { expose: false }) assert.strictEqual(err.expose, false) }) it('new createError.HttpError()', function () { assert.throws(function () { new createError.HttpError() // eslint-disable-line no-new }, /cannot construct abstract class/) }) it('new createError.NotFound()', function () { var err = new createError.NotFound() assert.strictEqual(err.name, 'NotFoundError') assert.strictEqual(err.message, 'Not Found') assert.strictEqual(err.status, 404) assert.strictEqual(err.statusCode, 404) assert.strictEqual(err.expose, true) assert(err.stack) }) it('new createError.InternalServerError()', function () { var err = new createError.InternalServerError() assert.strictEqual(err.name, 'InternalServerError') assert.strictEqual(err.message, 'Internal Server Error') assert.strictEqual(err.status, 500) assert.strictEqual(err.statusCode, 500) assert.strictEqual(err.expose, false) assert(err.stack) }) it('new createError["404"]()', function () { var err = new createError['404']() assert.strictEqual(err.name, 'NotFoundError') assert.strictEqual(err.message, 'Not Found') assert.strictEqual(err.status, 404) assert.strictEqual(err.statusCode, 404) assert.strictEqual(err.expose, true) assert(err.stack) }) it('should preserve error [[Class]]', function () { assert.strictEqual(Object.prototype.toString.call(createError('LOL')), '[object Error]') assert.strictEqual(Object.prototype.toString.call(new createError[404]()), '[object Error]') assert.strictEqual(Object.prototype.toString.call(new createError[500]()), '[object Error]') }) it('should support err instanceof Error', function () { assert(createError(404) instanceof Error) assert((new createError['404']()) instanceof Error) assert((new createError['500']()) instanceof Error) }) it('should support err instanceof exposed constructor', function () { assert(createError(404) instanceof createError.NotFound) assert(createError(500) instanceof createError.InternalServerError) assert((new createError['404']()) instanceof createError.NotFound) assert((new createError['500']()) instanceof createError.InternalServerError) assert((new createError.NotFound()) instanceof createError.NotFound) assert((new createError.InternalServerError()) instanceof createError.InternalServerError) }) it('should support err instanceof HttpError', function () { assert(createError(404) instanceof createError.HttpError) assert((new createError['404']()) instanceof createError.HttpError) assert((new createError['500']()) instanceof createError.HttpError) }) it('should support util.isError()', function () { /* eslint-disable node/no-deprecated-api */ assert(util.isError(createError(404))) assert(util.isError(new createError['404']())) assert(util.isError(new createError['500']())) /* eslint-enable node/no-deprecated-api */ }) })