{"_id":"errors","_rev":"1738569","name":"errors","description":"A comprehensive, robust, yet lightweight set of error utilities for node.js enabling you to do errors more effectively.","dist-tags":{"latest":"0.3.0"},"maintainers":[{"name":"boden","email":"bodenru@gmail.com"}],"time":{"modified":"2021-11-29T01:33:10.000Z","created":"2012-11-19T23:33:22.972Z","0.3.0":"2015-06-16T11:41:48.588Z","0.2.0":"2014-06-23T08:14:57.048Z","0.1.0":"2012-11-21T10:04:44.328Z","0.0.0":"2012-11-19T23:33:22.972Z"},"users":{"anmol1771":true,"jweyrich":true,"powmedia":true,"arielfr":true,"tregusti":true,"antanst":true,"jybleau":true,"ahmedfarooki":true,"traveltechymatt":true,"russiann":true},"author":{"name":"Boden Russell","email":"bodenru@gmail.com"},"repository":{"type":"git","url":"git://github.com/bodenr/errors.git"},"versions":{"0.3.0":{"name":"errors","version":"0.3.0","description":"A comprehensive, robust, yet lightweight set of error utilities for node.js enabling you to do errors more effectively.","keywords":["error","exceptions","express","connect","utilities"],"author":{"name":"Boden Russell","email":"bodenru@gmail.com"},"repository":{"type":"git","url":"git://github.com/bodenr/errors.git"},"main":"index","engines":{"node":"*"},"scripts":{"test":"make test"},"directories":{"doc":"./doc"},"devDependencies":{"mocha":"*","should":"< 2.0.0","supertest":"*","express":"< 4.0.0","markdox":"*","dox-foundation":"*"},"license":"MIT","gitHead":"af48c56267f4e27facb78f0c773498255f1f1966","bugs":{"url":"https://github.com/bodenr/errors/issues"},"homepage":"https://github.com/bodenr/errors","_id":"errors@0.3.0","_shasum":"572ed0fad82ab26ba04e797828f7103dd820732f","_from":".","_npmVersion":"1.4.14","_npmUser":{"name":"boden","email":"bodenru@gmail.com"},"maintainers":[{"name":"boden","email":"bodenru@gmail.com"}],"dist":{"shasum":"572ed0fad82ab26ba04e797828f7103dd820732f","size":37376,"noattachment":false,"key":"/errors/-/errors-0.3.0.tgz","tarball":"http://registry.cnpm.dingdandao.com/errors/download/errors-0.3.0.tgz"},"publish_time":1434454908588,"_cnpm_publish_time":1434454908588,"_hasShrinkwrap":false},"0.2.0":{"name":"errors","version":"0.2.0","description":"A comprehensive, robust, yet lightweight set of error utilities for node.js enabling you to do errors more effectively.","keywords":["error","exceptions","express","connect","utilities"],"author":{"name":"Boden Russell","email":"bodenru@gmail.com"},"repository":{"type":"git","url":"git://github.com/bodenr/errors.git"},"main":"index","engines":{"node":"*"},"scripts":{"test":"make test"},"directories":{"doc":"./doc"},"devDependencies":{"mocha":"*","should":"< 2.0.0","supertest":"*","express":"< 4.0.0","markdox":"*","dox-foundation":"*"},"license":"MIT","gitHead":"482430db3cfab16c0036fd0502e7de1e6021ccac","bugs":{"url":"https://github.com/bodenr/errors/issues"},"homepage":"https://github.com/bodenr/errors","_id":"errors@0.2.0","_shasum":"0f51e889daa3e11b19e7186d11f104aa66eb2403","_from":".","_npmVersion":"1.4.14","_npmUser":{"name":"boden","email":"bodenru@gmail.com"},"maintainers":[{"name":"boden","email":"bodenru@gmail.com"}],"dist":{"shasum":"0f51e889daa3e11b19e7186d11f104aa66eb2403","size":35955,"noattachment":false,"key":"/errors/-/errors-0.2.0.tgz","tarball":"http://registry.cnpm.dingdandao.com/errors/download/errors-0.2.0.tgz"},"publish_time":1403511297048,"_cnpm_publish_time":1403511297048,"_hasShrinkwrap":false},"0.1.0":{"name":"errors","version":"0.1.0","description":"A comprehensive, robust, yet lightweight set of error utilities for node.js enabling you to do errors more effectively.","keywords":["error","exceptions","express","connect","utilities"],"author":{"name":"Boden Russell","email":"bodensemail@gmail.com"},"repository":{"type":"git","url":"git://github.com/bodenr/errors.git"},"main":"index","engines":{"node":"*"},"scripts":{"test":"make test"},"directories":{"doc":"./doc"},"devDependencies":{"mocha":"*","should":"*","supertest":"*","express":"*","markdox":"*","dox-foundation":"*"},"license":"MIT","readmeFilename":"Readme.md","_id":"errors@0.1.0","dist":{"shasum":"1aca56c5b063d52f56958e0259fd3ddf35bff544","size":35954,"noattachment":false,"key":"/errors/-/errors-0.1.0.tgz","tarball":"http://registry.cnpm.dingdandao.com/errors/download/errors-0.1.0.tgz"},"_npmVersion":"1.1.65","_npmUser":{"name":"boden","email":"bodensemail@gmail.com"},"maintainers":[{"name":"boden","email":"bodenru@gmail.com"}],"publish_time":1353492284328,"_cnpm_publish_time":1353492284328,"_hasShrinkwrap":false},"0.0.0":{"name":"errors","version":"0.0.0","description":"ERROR: No README.md file found!","main":"index.js","scripts":{"test":"exit 0"},"repository":"","author":"","license":"BSD","_id":"errors@0.0.0","dist":{"shasum":"ea37d2da68699a0b2754974f2a151defefc2d2cf","size":259,"noattachment":false,"key":"/errors/-/errors-0.0.0.tgz","tarball":"http://registry.cnpm.dingdandao.com/errors/download/errors-0.0.0.tgz"},"_npmVersion":"1.1.65","_npmUser":{"name":"isaacs","email":"i@izs.me"},"maintainers":[{"name":"boden","email":"bodenru@gmail.com"}],"directories":{},"publish_time":1353368002972,"_cnpm_publish_time":1353368002972,"_hasShrinkwrap":false}},"readme":"[![Build Status](https://secure.travis-ci.org/bodenr/errors.png)](http://travis-ci.org/bodenr/errors)\n# errors\n    \nErrors is a comprehensive and robust, yet lightweight, set of error utilities for \n[node.js](http://nodejs.org) enabling you to _do_ errors more effectively.\n\n## Features\n\n* Parameterized error factory allowing you do define how errors should behave \nbased on your project needs.\n* Support for enterprise level error attributes including more detailed error cause\nand operator response messages.\n* Predefined error constructors for all HTTP 4xx-5xx based errors allowing you to leverage\nHTTP errors out of the box.\n* [express.js](http://expressjs.com/) integration permitting your code to `send()` any\ntype of `Error` directly using Express's `response` object.\n* [connect.js](http://www.senchalabs.org/connect/) support allowing you to use custom\nerrors with connect's `errorHandler` middleware or this libraries custom error handler\nmiddleware.\n* Error mapping via registered mapping function permitting you to map between \nerrors when needed.\n\n## Installation\n\nInstall using `npm`:\n\n    $ npm install errors\n\n## Running the tests\n\nFrom the `errors` directory first install the dev dependencies:\n```\nnpm install\n```\n\nThen run the tests:\n```\nnpm test\n```\n\n## API Docs\n\nThe API docs are provided in html and md format and are located under\n`errors/docs/`. If you want to rebuild them for any reason, you can\nrun the following from the `errors` directory:\n```\nmake doc\n```\n\n## Defining error messages\n\nThe examples assume you've `require`d the errors module like so:\n```js\nrequire('errors');\n```\n\nCreate a very barebones error -- you must specify at least the error name:\n\n```js\n// barebones\nerrors.create({name: 'RuntimeError'});\nconsole.log(new errors.RuntimeError().toString());\n```\n\nproduces:\n```\nRuntimeError: An unexpected RuntimeError occurred.\nCode: 601\n```\n\nYou can define a default message for the error:\n\n```js\n// default message\nerrors.create({\n    name: 'RuntimeError',\n    defaultMessage: 'A runtime error occurred during processing'\n});\nconsole.log(new errors.RuntimeError().toString());\n```\n\nwhich outputs:\n```\nRuntimeError: A runtime error occurred during processing\nCode: 602\n\n```\n\nDefine a default message, explanation and response:\n\n```js\n// default message, explanation and response\nerrors.create({\n    name: 'FileNotFoundError',\n    defaultMessage: 'The requested file could not be found',\n    defaultExplanation: 'The file /home/boden/foo could not be found',\n    defaultResponse: 'Verify the file exists and retry the operation'\n});\nconsole.log(new errors.FileNotFoundError().toString());\n```\n\ngives us:\n```\nFileNotFoundError: The requested file could not be found\nCode: 603\nExplanation: The file /home/boden/foo could not be found\nResponse: Verify the file exists and retry the operation\n\n```\n\nOverride messages on instantiation:\n```js\n// override messages\nconsole.log(new errors.FileNotFoundError(\n        'Cannot read file'\n        , 'You do not have access to read /root/foo'\n        , 'Request a file you have permissions to access').toString());\n```\n\noutputs:\n```\nFileNotFoundError: Cannot read file\nCode: 603\nExplanation: You do not have access to read /root/foo\nResponse: Request a file you have permissions to access\n\n```\n\nUse the options style constructor to assign standard properties:\n```js\nconsole.log(new errors.Http401Error({\n\tmessage: \"Expired Token\",\n\texplanation: \"Your token has expired\"}).toString());\n```\n\noutputs:\n```\nHttp401Error: Expired Token\nCode: 401\nExplanation: Your token has expired\nError: Expired Token\n```\n\nUsing the options style constructor you can also assign\narbitrary non-standard properties:\n```js\nconsole.log(new errors.Http401Error({\n\tmessage: \"Expired Token\",\n\texplanation: \"Your token has expired\",\n\texpired: new Date()}).toString());\n```\n\noutputs:\n```\nHttp401Error: Expired Token\nCode: 401\nExplanation: Your token has expired\nexpired: Fri Jun 20 2014 04:19:41 GMT-0400 (EDT)\n```\n\nNote however that you cannot assign values to the\n`stack`, `name` or `code` standard property:\n```js\nconsole.log(new errors.Http401Error({\n\tname: \"ExpiredToken\"}).toString());\n```\n\noutputs:\n```\n/home/boden/workspace/errors/lib/errors.js:261\n    \t\t\tthrow Error(\"Properties 'stack', 'name' or 'code' \" +\n    \t\t\t      ^\nError: Properties 'stack', 'name' or 'code' cannot be overridden\n    at Error (<anonymous>)\n    at new scope.(anonymous function) (/home/boden/workspace/errors/lib/errors.js:261:14)\n    at Object.<anonymous> (/home/boden/workspace/errors/examples/basic/usage.js:126:13)\n    at Module._compile (module.js:456:26)\n    at Object.Module._extensions..js (module.js:474:10)\n    at Module.load (module.js:356:32)\n    at Function.Module._load (module.js:312:12)\n    at Function.Module.runMain (module.js:497:10)\n    at startup (node.js:119:16)\n    at node.js:906:3\n```\n\n## Error codes\n\nIf you don't provide a `code` when defining the error, a unique code will\nbe assigned for you. Unique codes start at 600 and increase by 1 for each\nerror defined.\n\nIf you prefer to manage your own error codes, for example to group related\nerrors into blocks of codes, just specify a `code`:\n```js\n// define code\nerrors.create({\n    name: 'SecurityError',\n    code: 1100\n});\nconsole.log(new errors.SecurityError().toString());\n```\n\nwhich logs:\n```\nSecurityError: An unexpected SecurityError occurred.\nCode: 1100\n\n```\n\n## Inheritance\n\nYou can build a hierarchy of errors by specifying the `parent` your\nerror should inherit from. If no `parent` is specified, the error\nwill inherit from `Error`.\n\nFor example:\n```js\n// inheritance\nerrors.create({\n    name: 'FatalError',\n    defaultMessage: 'A fatal error occurred',\n});\nerrors.create({\n    name: 'FatalSecurityError',\n    defaultMessage: 'A security error occurred, the app must exit',\n    parent: errors.FatalError\n});\ntry {\n    throw new errors.FatalSecurityError();\n} catch (e) {\n    if (e instanceof errors.FatalError) {\n        // exit\n        console.log(\"Application is shutting down...\");\n    }\n}\n```\n\nwill produce:\n```\nApplication is shutting down...\n```\n\n## Namespacing\n\nBy default, newly defined errors are created on the `exports` of\nthe errors module, but you can specify where the error should\nbe defined.\n\nFor example to define an error on your module's `exports`:\n```js\n// namespace\nerrors.create({\n    name: 'MalformedExpressionError',\n    scope: exports\n});\nconsole.log(new exports.MalformedExpressionError().toString());\n```\n\n## Looking up errors\n\nFor convenience, errors keeps track of all the errors you've defined\nvia the errors module and allows you to look them up via `name` or\n`code`.\n\nSo from our previous example:\n```js\nerrors.find(1100);\nerrors.find('SecurityError')\n```\n\nWill both return the `SecutiryError` we defined.\n\n## Stack traces\n\nBy default stack traces are disabled which means that error methods\nlike `toString()` and `toJSON()` return representation without stack \ntraces. You can enable stack traces by leveraging the `errors.stacks()`\nmethod.\n\nFor example:\n```js\nerrors.stacks(true);\nnew errors.Http413Error().toString();\n// => includes stack trace\nnew errors.Http413Error().toJSON();\n// => includes a 'stack' property\n```\n\nYou can also use the `errors.stacks()` method without arguments to \nretrieve the current value of stacks.\n\nThis allows you to write code like:\n```js\nif (errors.stacks()) {\n    // => stack traces enabled\n}\n```\n\n## Mappers\n\nYou can register and leverage mapper functions which allow you to\nmap from one (or more) error types into another.\n\nFor example if you wanted to mask invalid user and password errors into\na generic credentials error:\n```js\n// mappers\nerrors.create({name: 'InvalidUsernameError'});\nerrors.create({name: 'InvalidPasswordError'});\nerrors.mapper(['InvalidUsernameError', 'InvalidPasswordError'], function(err) {\n    return new errors.SecurityError('Invalid credentials supplied');\n});\nconsole.log(errors.mapError(new errors.InvalidUsernameError()).toString());\nconsole.log(errors.mapError(new errors.InvalidPasswordError()).toString());\n```\n\noutputs:\n```\nSecurityError: Invalid credentials supplied\nCode: 1100\nSecurityError: Invalid credentials supplied\nCode: 1100\n\n```\n\n## Native errors\n\nOften times you need to extract 'errors-like' properties from native error\nobjects. For example you have a native JS or node error and you want to \nextract it's errors-like properties. An error's module-level function\ncalled `errors.errorToJSON()` allows you to do this.\n\nFor example to extract error properties from a native error (`errors.stacks`\nis set to `false` in this example):\n```js\nconsole.log(\"%j\", errors.errorToJSON(new TypeError(\"Bad type\")));\n```\n\noutputs:\n```\n{\"message\":\"Bad type\",\"name\":\"TypeError\"}\n```\n\nYou can also remap error attributes which may be nested. For example:\n\n```js\nconsole.log(\"%j\", errors.errorToJSON(new TypeError(\"Bad type\"), \n    {'className': ['constructor.name'], 'message': ['message']}));\n```\n\noutputs:\n```\n{\"className\":\"TypeError\",\"message\":\"Bad type\"}\n```\n\n\n## Predefined HTTP 4xx-5xx errors\n\nThe errors module predefines a set of errors which represent HTTP\n4xx-5xx responses. These errors are exported by the errors module and use the\nnaming convention `Http[code]Error`. For example `Http401Error` and \n`Http500Error` which have a code of `401` and `500` respectively.\n\nFor example to leverage the HTTP errors:\n```js\nthrow new errors.Http401Error();\n// ...\nthrow new errors.Http500Error('Something bad happened');\n```\n\n## Connect/Express middleware integration\n\n**Compatibility**\nErrors version 0.1.0 only works with Express < 4.0.0. \n\nYou can use your custom errors with connect's or express's `errorHandler()`\nmiddleware as you might expect:\n\n```js\n// ...\napp.use(function(req, res, next) {\n    // bubble up to errorHandler\n    throw new errors.Http401Error();\n});\napp.use(express.errorHandler());\n// ...\n```\nHowever due to the additional information captured in custom errors\nsuch as the `response` and `explanation`, the default HTML formatting\nof connect/express `errorHandler()` is not as pretty as you might like.\n\nTherefore errors provides its own flavor of middleware.\n\nIn its simplest form just use `errors.errorHandler()` as you would do with\nconnect or express. This simple form of the middleware will include the \nadditional datums stored in the custom error such as the `explanation`\nand `response`. But the `errors.errorHandler()` middleware also accepts \nsome optional arguments to customize its behavior.\n\nSpecifically you can set the title to use for HTML based responses, override\nif the stack should be included and also specify if the middleware should \nuse `connectCompat` mode. In `connectCompat` mode the HTML based responses\nlook exactly as they would with connect/express `errorHandler()` and do \nnot include the additional datums from your error.\n\nFor example\n```js\n// ...\napp.use(errors.errorHandler({title: 'Errors Middleware', includeStack: true}));\n// ...\n```\nbinds the errors `errorHandler` using a custom title and which will include \nstack traces. Note that using the `includeStack` property overrides the \ncurrent value of `errors.stacks()`.\n\n## Express send integration\n\nWhen the errors module is first imported, it determines if `express` is\ninstalled. If express is installed, errors automatically patches `express`'s \n`response.send()` method to support `send()`ing `Error` based objects.\n\nSo the following is valid:\n```js\napp.get('/users/:user', function(req, res) {\n    users.get(req.params.user, function(err, user) {\n        return res.send(err || user || new errors.Http404Error('User does not exist'));\n    });\n});\n```\n\nBy default both vanilla errors (those provided by the JS runtime) and errors\nwhich have a `code` which is not a valid HTTP status code are mapped to a `500`\nresponse.\n\nSo:\n```js\nres.send(new Error('Vanilla JS error'));\n```\n\nand\n```js\nres.send(new errors.find('MyErrorName'));\n```\n\nboth will result in a `500` response.\n\nMappers can also be used with `express`'s `send()` method.\n\nFor example:\n```js\nerrors.mapper('RangeError', function(rangeError) {\n    return new errors.Http412Error('Invalid range requested');\n})\n.mapper('ReferenceError', function(refError) {\n    return new errors.Http424Error('Bad reference given');\n})\n.mapper('SyntaxError', function(syntaxError) {\n    return new errors.Http400Error('Invalid syntax');\n});\n\n// ...\n\nres.send(new RangeError());\n// => 412 response as per mapper\n\nres.send(new ReferenceError());\n// => 424 response as per mapper\n\nres.send(new SyntaxError());\n// => 400 response as per mapper\n```\n\nThe implementation provides direct support for `application/json`, \n`text/html` and `text/plain` content types. If the `request` specifies\na different `Accept` type, the response defaults to `text/plain`. Moreover\n`application/json` responses provide a complete _JSONifed_ representation\nof the error.\n\nFor example the following setup:\n```js\nerrors.create({\n    name: 'DatabaseConnectionError',\n    defaultExplanation: 'Unable to connect to configured database.',\n    defaultResponse: 'Verify the database is running and reachable.'\n});\n\n// ...\nres.send(new errors.DatabaseConnectionError());\n```\n\nWill produce the JSON response below when `application/json`\nis used as the accept type:\n```\n{\n    \"explanation\": \"Unable to connect to configured database.\",\n    \"response\": \"Verify the database is running and reachable.\",\n    \"code\": 601,\n    \"status\": 500,\n    \"name\": \"DatabaseConnectionError\",\n    \"message\": \"An unexpected DatabaseConnectionError occurred.\"\n}\n```\n\nFor HTML based responses, `send()`ing an error will produce a HTML \nresponse that looks like express's or connect's `errorHandler()` middleware. \nThat is, it's an HTML page with minimal styling. Moreover you can control \nthe HTML response page title using the `errors.title('My Title')` method. \nYou can also control if stack traces should be included in the `send()` by \nusing the `errors.stacks()` method. \n\n## License\n\n(The MIT License)\n\nCopyright (c) 2012 Boden Russell &lt;bodensemail@gmail.com&gt;\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","_attachments":{},"homepage":"https://github.com/bodenr/errors","bugs":{"url":"https://github.com/bodenr/errors/issues"},"license":"MIT"}