{"name":"error","version":"3.0.0","description":"Custom errors","keywords":[],"author":{"name":"Raynos","email":"raynos2@gmail.com"},"repository":{"type":"git","url":"git://github.com/Raynos/error.git"},"main":"index","homepage":"https://github.com/Raynos/error","contributors":[{"name":"Raynos"}],"bugs":{"url":"https://github.com/Raynos/error/issues","email":"raynos2@gmail.com"},"dependencies":{"xtend":"~2.1.1","string-template":"~0.1.3"},"devDependencies":{"tape":"~1.0.2"},"licenses":[{"type":"MIT","url":"http://github.com/Raynos/error/raw/master/LICENSE"}],"scripts":{"test":"node ./test.js","start":"node ./index.js","watch":"nodemon -w ./index.js index.js","travis-test":"istanbul cover ./test/index.js && ((cat coverage/lcov.info | coveralls) || exit 0)","cover":"istanbul cover --report none --print detail ./test/index.js","view-cover":"istanbul report html && google-chrome ./coverage/index.html","test-browser":"testem-browser ./test/browser/index.js","testem":"testem-both -b=./test/browser/index.js"},"testling":{"files":"test/index.js","browsers":["ie/8..latest","firefox/16..latest","firefox/nightly","chrome/22..latest","chrome/canary","opera/12..latest","opera/next","safari/5.1..latest","ipad/6.0..latest","iphone/6.0..latest","android-browser/4.2..latest"]},"_id":"error@3.0.0","dist":{"shasum":"a2957dcfd02e66cced07c120d20b6fbf7f9d8d78","tarball":"http://registry-npm.ywwl.com/error/download/error-3.0.0.tgz","integrity":"sha512-dv4mBdBFVJN+WFQai8QCCnM9zTnfOZuXSG8A3KbrDC0TJt1sNb8NTSn961yY8Qp8L2hwcdUcOvUiiKKwILyAlQ==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIEUAs3eJgtjHgHd9xkbAK8l8Qxb7O6rtqJS4xtR4LZdNAiBudI+0BWaD2BBtuLrjMp27885Y2+xec2aScqcc+KtDOg=="}],"size":2455,"noattachment":false,"key":"/error/-/error-3.0.0.tgz"},"_from":".","_npmVersion":"1.3.8","_npmUser":{"name":"raynos","email":"raynos2@gmail.com"},"maintainers":[{"name":"raynos","email":"raynos2@gmail.com"}],"directories":{},"readme":"# error\r\n\r\nWrap errors with more context.\r\n\r\n## Inspiration\r\n\r\nThis module is inspired by the go error libraries that have simple\r\nfunctions for creating & wrapping errors.\r\n\r\nThis is based on libraries like [eris][eris] & [pkg/errors][pkg-errors]\r\n\r\n## Older version of `error`\r\n\r\nIf you are looking for the older v7 version of error you should\r\ncheck [v7.x][7.x] branch\r\n\r\n## Using `error` with `async` / `await`\r\n\r\nCheck out [`resultify`](https://www.npmjs.com/package/resultify) !\r\n\r\nThe rest of the examples use plain vanilla callbacks.\r\n\r\n## Motivation\r\n\r\nWrapping errors when bubbling up instead of just doing\r\n`if (err) return cb(err)` allows you to pass more context\r\nup the stack.\r\n\r\nCommon example include passing along parameters from the DB\r\nread related to the failure or passing along any context\r\nfrom the user in a HTTP request when doing a failure.\r\n\r\nThis can give you nice to read messages that include more\r\ninformation about the failure as it bubbles up.\r\n\r\nThere is more information about how to handle errors in this\r\narticle [Don't just check errors, handle them gracefully][dave]\r\n\r\nIf you want a deep dive into the difference between\r\n[Programming and Operational errors](https://www.joyent.com/node-js/production/design/errors)\r\nplease check out [this guide](https://www.joyent.com/node-js/production/design/errors)\r\n\r\nexamples:\r\n\r\n```js\r\nconst { wrapf } = require('error')\r\n\r\nfunction authenticatRequest(req) {\r\n  authenticate(req.user, (err) => {\r\n    if (err) {\r\n      return cb(wrapf('authenticate failed', err))\r\n    }\r\n    cb(null)\r\n  })\r\n}\r\n```\r\n\r\nor\r\n\r\n```js\r\nconst { wrapf } = require('error')\r\n\r\nfunction readFile(path, cb) {\r\n  fs.open(path, 'r', (err, fd) => {\r\n    if (err) {\r\n      return cb(wrapf('open failed', err, { path }))\r\n    }\r\n\r\n    const buf = Buffer.alloc(64 * 1024)\r\n    fs.read(fd, buf, 0, buf.length, 0, (err) => {\r\n      if (err) {\r\n        return cb(wrapf('read failed', err, { path }))\r\n      }\r\n\r\n      fs.close(fd, (err) => {\r\n        if (err) {\r\n          return cb(wrapf('close failed', err, { path }))\r\n        }\r\n\r\n        cb(null, buf)\r\n      })\r\n    })\r\n  })\r\n}\r\n```\r\n\r\n## Structured errors\r\n\r\n```js\r\nconst { SError } = require('error')\r\n\r\nclass ServerError extends SError {}\r\nclass ClientError extends SError {}\r\n\r\nconst err = ServerError.create(\r\n  '{title} server error, status={statusCode}', {\r\n    title: 'some title',\r\n    statusCode: 500\r\n  }\r\n)\r\nconst err2 = ClientError.create(\r\n  '{title} client error, status={statusCode}', {\r\n    title: 'some title',\r\n    statusCode: 404\r\n  }\r\n)\r\n```\r\n\r\n## Wrapped Errors\r\n\r\n```js\r\nconst net = require('net');\r\nconst { WError } = require('error')\r\n\r\nclass ServerListenError extends WError {}\r\n\r\nvar server = net.createServer();\r\n\r\nserver.on('error', function onError(err) {\r\n  if (err.code === 'EADDRINUSE') {\r\n    throw ServerListenFailedError.wrap(\r\n      'error in server, on port={requestPort}', err, {\r\n        requestPort: 3000,\r\n        host: null\r\n      }\r\n    )\r\n  } else {\r\n    throw err;\r\n  }\r\n});\r\n\r\nserver.listen(3000);\r\n```\r\n\r\n## Comparison to Alternatives.\r\n\r\nThere are alternative existing libraries for creating typed\r\nand wrapped errors on npm. Here's a quick comparison to some\r\nalternatives.\r\n\r\n### [`verror`][verror]\r\n\r\nThis module takes inspiration from `verror` and adds improvements.\r\n - You can pass extra fields as meta data on the error\r\n - The templating forces dynamic strings to be extra fields.\r\n - Uses ES6 classes for inheritance. This gives your errors unique\r\nclass names and makes them show up in heapdumps.\r\n - Has JSON.stringify support\r\n\r\n### [`error@7.x`][7.x]\r\n\r\nThis package used to have a completely different API on the\r\n[7.x][7.x] branch.\r\n - New `error` module uses actual classes instead of dynamically\r\nmonkey patching fields onto `new Error()`\r\n - Implementation is more static, previous code was very dynamic\r\n - Simpler API, see the message & properties in one place.\r\n - `wrapf` & `errorf` helpers for less boilerplate.\r\n\r\n### Hand writing `Error` sub classes.\r\n\r\nYou can create your own Error classes by hand. This tends to lead\r\nto 10-20 lines of boilerplate per error which is replace with\r\none line by using the `error` module; aka\r\n\r\n```js\r\nclass AccountsServerFailureError extends SError {}\r\nclass ConnectionResetError extends WError {}\r\n```\r\n\r\n### [`ono`][ono]\r\n\r\nThe `ono` package has similar functionality with a different API\r\n - `ono` encourages plain errors instead of custom errors by default\r\n - `error` has zero dependencies\r\n - `error` is only one simple file. `ono` is 10.\r\n - `error` implementation is more static, ono is very dynamic.\r\n\r\n## Documentation\r\n\r\nThis package implements three classes, `WError`; `SError` &\r\n`MultiError`\r\n\r\nYou are expected to subclass either `WError` or `SError`;\r\n\r\n - `SError` stands for `Structured Error`; it's an error base\r\n    class for adding informational fields to your error beyond\r\n    just having a message.\r\n - `WError` stands for `Wrapped Error`; it's an error base\r\n    class for when you are wrapping an existing error with more\r\n    information.\r\n\r\nThe `MultiError` class exists to store an array of errors but\r\nstill return a single `Error`; This is useful if your doing\r\na parallel operation and you want to wait for them all to finish\r\nand do something with all of the failures.\r\n\r\nSome utility functions are also exported:\r\n - `findCauseByName`; See if error or any of it's causes is of\r\nthe type name.\r\n - `fullStack`; Take a wrapped error and compute a full stack.\r\n - `wrapf`; Utility function to quickly wrap\r\n - `errorf`; Utility function to quickly create an error\r\n - `getInfo`; Utility function to get the info for any error\r\nobject. Calls `err.info()` if the method exists.\r\n\r\n### `WError`\r\n\r\nExample:\r\n\r\n```js\r\nclass ServerListenError extends WError {}\r\n\r\nServerListenError.wrap('error in server', err, {\r\n  port: 3000\r\n})\r\n```\r\n\r\nWhen using the `WError` class it's recommended to always call\r\nthe static `wrap()` method instead of calling the constructor\r\ndirectly.\r\n\r\nExample (without cause message):\r\n\r\n```js\r\nclass ApplicationStartupError extends WError {}\r\n\r\nApplicationStartupError.wrap(\r\n  'Could not start the application cleanly: {reason}',\r\n  err,\r\n  {\r\n    skipCauseMessage: true,\r\n    reason: 'Failed to read from disk'\r\n  }\r\n)\r\n```\r\n\r\nSetting `skipCauseMessage: true` will not append the cause\r\nerror message but still make the cause object available.\r\n\r\n### `const werr = new WError(message, cause, info)`\r\n\r\nInternal constructor, should pass a `message` string, a `cause`\r\nerror and a `info` object (or `null`).\r\n\r\n### `WError.wrap(msgTmpl, cause, info)`\r\n\r\n`wrap()` method to create error instances. This applies the\r\n[`string-template`][string-template] templating to `msgTmpl`\r\nwith `info` as a parameter.\r\n\r\nThe `cause` parameter must be an `error`\r\nThe `info` parameter is an object or `null`.\r\n\r\nThe `info` parameter can contain the field `skipCauseMessage: true`\r\nwhich will make `WError` not append `: ${causeMessage}` to the\r\nmessage of the error.\r\n\r\n### `werr.type`\r\n\r\nThe `type` field is the machine readable type for this error.\r\nAlways use `err.type` and never `err.message` when trying to\r\ndetermine what kind of error it is.\r\n\r\nThe `type` field is unlikely to change but the `message` field\r\ncan change.\r\n\r\n### `werr.fullType()`\r\n\r\nCalling `fullType` will compute a full type for this error and\r\nany causes that it wraps. This gives you a long `type` string\r\nthat's a concat for every wrapped cause.\r\n\r\n### `werr.cause()`\r\n\r\nReturns the `cause` error.\r\n\r\n### `werr.info()`\r\n\r\nReturns the `info` object passed on. This is merged with the\r\ninfo of all `cause` errors up the chain.\r\n\r\n### `werr.toJSON()`\r\n\r\nThe `WError` class implements `toJSON()` so that the JSON\r\nserialization makes sense.\r\n\r\n### `WError.fullStack(err)`\r\n\r\nThis returns a full stack; which is a concatenation of this\r\nstack trace and the stack trace of all causes in the cause chain\r\n\r\n### `WError.findCauseByName(err, name)`\r\n\r\nGiven an err and a name will find if the err or any causes\r\nimplement the type of that name.\r\n\r\nThis allows you to check if a wrapped `ApplicationError` has\r\nfor example a `LevelReadError` or `LevelWriteError` in it's cause\r\nchain and handle database errors differently from all other app\r\nerrors.\r\n\r\n### `SError`\r\n\r\nExample:\r\n\r\n```js\r\nclass LevelReadError extends SError {}\r\n\r\nLevelReadError.create('Could not read key: {key}', {\r\n  key: '/some/key'\r\n})\r\n```\r\n\r\nWhen using the `SError` class it's recommended to always call\r\nthe static `create()` method instead of calling the constructor\r\ndirectly.\r\n\r\n### `const serr = new SError(message, info)`\r\n\r\nInternal constructor that takes a message string & an info object.\r\n\r\n### `SError.create(messageTmpl, info)`\r\n\r\nThe main way to create error objects, takes a message template\r\nand an info object.\r\n\r\nIt will use [string-template][string-template] to apply the\r\ntemplate with the `info` object as a parameter.\r\n\r\n### `SError.getInfo(error)`\r\n\r\nStatic method to `getInfo` on a maybe error. The `error` can\r\nbe `null` or `undefined`, it can be a plain `new Error()` or\r\nit can be a structured or wrapped error.\r\n\r\nWill return `err.info()` if it exists, returns `{}` if its `null`\r\nand returns `{ ...err }` if its a plain vanilla error.\r\n\r\n### `serr.type`\r\n\r\nReturns the type field. The `err.type` field is machine readable.\r\nAlways use `err.type` & not `err.message` when trying to compare\r\nerrors or do any introspection.\r\n\r\nThe `type` field is unlikely to change but the `message` field\r\ncan change.\r\n\r\n### `serr.info()`\r\n\r\nReturns the info object for this error.\r\n\r\n### `serr.toJSON()`\r\n\r\nThis class can JSON serialize cleanly.\r\n\r\n### `MultiError`\r\n\r\nExample:\r\n\r\n```js\r\nclass FanoutError extends MultiError {}\r\n\r\nfunction doStuff (filePath, cb) {\r\n  fanoutDiskReads(filePath, (errors, fileContents) => {\r\n    if (errors && errors.length > 0) {\r\n      const err = FanoutError.errorFromList(errors)\r\n      return cb(err)\r\n    }\r\n\r\n    // do stuff with files.\r\n  })\r\n}\r\n```\r\n\r\nWhen using the `MultiError` class it's recommended to always\r\ncall the static `errorFromList` method instead of calling the\r\nconstructor directly.\r\n\r\n## Usage from typescript\r\n\r\nThe `error` library does not have an `index.d.ts` but does have\r\nfull `jsdoc` annotations so it should be typesafe to use.\r\n\r\nYou will need to configure your `tsconfig` appropiately ...\r\n\r\n```json\r\n{\r\n  \"compilerOptions\": {\r\n    ...\r\n    \"allowJs\": true,\r\n    ...\r\n  },\r\n  \"include\": [\r\n    \"src/**/*.js\",\r\n    \"node_modules/error/index.js\"\r\n  ],\r\n  \"exclude\": [\r\n    \"node_modules\"\r\n  ]\r\n}\r\n```\r\n\r\nTypescript does not understand well type source code in\r\n`node_modules` without an `index.d.ts` by default, so you\r\nneed to tell it to include the implementation of `error/index.js`\r\nduring type checking and to `allowJs` to enable typechecking\r\njs + jsdoc comments.\r\n\r\n## Installation\r\n\r\n`npm install error`\r\n\r\n## Contributors\r\n\r\n - Raynos\r\n\r\n## MIT Licenced\r\n\r\n  [eris]: https://github.com/rotisserie/eris/tree/v0.1.0\r\n  [pkg-errors]: https://github.com/pkg/errors\r\n  [7.x]: https://github.com/Raynos/error/tree/v7.x\r\n  [dave]: https://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully\r\n  [string-template]: https://github.com/Matt-Esch/string-template\r\n  [verror]: https://github.com/joyent/node-verror\r\n  [ono]: https://github.com/JS-DevTools/ono\r\n","publish_time":1394761682567,"_cnpm_publish_time":1394761682567,"dist-tags":{"experiment":"6.0.0-experiment3","latest":"10.4.0"}}