{"id":22030953,"url":"https://github.com/ts-stack/chain-error","last_synced_at":"2026-02-08T22:03:45.547Z","repository":{"id":50762704,"uuid":"181320166","full_name":"ts-stack/chain-error","owner":"ts-stack","description":"chain-error: rich JavaScript errors","archived":false,"fork":false,"pushed_at":"2024-12-29T07:34:17.000Z","size":539,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-14T22:38:51.014Z","etag":null,"topics":["chain-error","error-handler","error-messages","errors"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ts-stack.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-04-14T14:21:34.000Z","updated_at":"2024-12-29T07:34:21.000Z","dependencies_parsed_at":"2022-09-10T19:31:46.172Z","dependency_job_id":null,"html_url":"https://github.com/ts-stack/chain-error","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-stack%2Fchain-error","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-stack%2Fchain-error/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-stack%2Fchain-error/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-stack%2Fchain-error/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ts-stack","download_url":"https://codeload.github.com/ts-stack/chain-error/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252874210,"owners_count":21817781,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["chain-error","error-handler","error-messages","errors"],"created_at":"2024-11-30T08:12:36.666Z","updated_at":"2026-02-08T22:03:41.611Z","avatar_url":"https://github.com/ts-stack.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# chain-error: rich JavaScript errors\n\nThis is a fork of [VError](https://github.com/joyent/node-verror).\n\nThe `ChainError` support:\n\n* chains of causes\n* properties to provide extra information about the error\n* creating your own subclasses that support all of these\n\n`ChainError` chaining errors while preserving each one's error message.\nThis is useful in servers and command-line utilities when you want to\npropagate an error up a call stack, but allow various levels to add their own\ncontext. See examples below.\n\nYou can hiding the lower-level messages from the\ntop-level error. This is useful for API endpoints where you don't want to\nexpose internal error messages, but you still want to preserve the error chain\nfor logging and debugging.\n\n\n# Quick start\n\nFirst, install the package:\n\n```bash\nnpm install @ts-stack/chain-error\n```\n\nIf nothing else, you can use `ChainError` as a drop-in replacement for the built-in\nJavaScript `Error` class:\n\n```ts\nimport { ChainError } from '@ts-stack/chain-error';\n\nconst path = '/etc/passw';\nconst err = new ChainError(`missing file: \"${path}\"`);\nconsole.log(err.message);\n```\n\nThis prints:\n\n```text\nmissing file: \"/etc/passwd\"\n```\n\nYou can also pass a `cause` argument, which is any other `Error` instance:\n\n```ts\nconst err1 = new Error('No such file or directory');\nconst err2 = new ChainError('failed to stat \"/junk\"', err1);\nconst err3 = new ChainError('request failed', err2);\nconsole.error(err3.message);\n```\n\nThis prints:\n\n```text\nrequest failed: failed to stat \"/junk\": No such file or directory\n```\n\nThe idea is that each layer in the stack annotates the error with a description\nof what it was doing. The end result is a message that explains what happened\nat each level.\n\nYou can also decorate Error objects with additional information so that callers\ncan not only handle each kind of error differently, but also construct their own\nerror messages (e.g., to localize them, format them, group them by type, and so\non). See the example below.\n\n\n# Deeper dive\n\nThe two main goals for `ChainError` are:\n\n* **Make it easy to construct clear, complete error messages intended for\n  people.**  Clear error messages greatly improve both user experience and\n  debuggability, so we wanted to make it easy to build them.\n* **Make it easy to construct objects with programmatically-accessible\n  metadata** (which we call _informational properties_). Instead of just saying\n  \"connection refused while connecting to 192.168.1.2:80\", you can add\n  properties like `\"ip\": \"192.168.1.2\"` and `\"tcpPort\": 80`. This can be used\n  for feeding into monitoring systems, analyzing large numbers of errors (as\n  from a log file), or localizing error messages.\n\nTo really make this useful, it also needs to be easy to compose errors:\nhigher-level code should be able to augment the errors reported by lower-level\ncode to provide a more complete description of what happened. Instead of saying\n\"connection refused\", you can say \"operation X failed: connection refused\".\nThat's why `ChainError` supports `causes`.\n\nIn order for all this to work, programmers need to know that it's generally safe\nto wrap lower-level errors with higher-level ones. If you have existing code\nthat handles errors produced by a library, you should be able to wrap those\nerrors with a `ChainError` to add information without breaking the error handling\ncode. There are two obvious ways that this could break such consumers:\n\n* The error's name might change. People typically use `name` to determine what\n  kind of Error they've got. To ensure compatibility, you can create `ChainError`\n  with custom names, but this approach isn't great because it prevents you from\n  representing complex failures. For this reason, `ChainError` provides\n  `findCauseByName`, which essentially asks: does this Error _or any of its\n  causes_ have this specific name?  If error handling code uses\n  `findCauseByName`, then subsystems can construct very specific causal chains\n  for debuggability and still let people handle simple cases easily. There's an\n  example below.\n* The error's properties might change. People often hang additional properties\n  off of `Error` objects. If we wrap an existing `Error` in a new `Error`, those\n  properties would be lost unless we copied them. But there are a variety of\n  both standard and non-standard `Error` properties that should _not_ be copied in\n  this way: most obviously `name`, `message`, and `stack`, but also `fileName`,\n  `lineNumber`, and a few others. Plus, it's useful for some Error subclasses\n  to have their own private properties -- and there'd be no way to know whether\n  these should be copied. For these reasons, `ChainError` first-classes these\n  information properties. You have to provide them in the constructor, you can\n  only fetch them with the `getInfo()` function, and `ChainError` takes care of making\n  sure properties from causes wind up in the `getInfo()` output.\n\nLet's put this all together with an example from the `node-fast` RPC library.\n`node-fast` implements a simple RPC protocol for Node programs. There's a server\nand client interface, and clients make RPC requests to servers. Let's say the\nserver fails with an `UnauthorizedError` with message `user 'bob' is not\nauthorized`. The client wraps all server errors with a FastServerError. The\nclient also wraps all request errors with a `FastRequestError` that includes the\nname of the RPC call being made. The result of this failed RPC might look like\nthis:\n\n```text\nname: FastRequestError\nmessage: \"request failed: server error: user 'bob' is not authorized\"\nrpcMsgid: \u003cunique identifier for this request\u003e\nrpcMethod: GetObject\ncause:\n  name: FastServerError\n  message: \"server error: user 'bob' is not authorized\"\n  cause:\n  name: UnauthorizedError\n  message: \"user 'bob' is not authorized\"\n  rpcUser: \"bob\"\n```\n\nWhen the caller uses `ChainError.getInfo()`, the information properties are collapsed\nso that it looks like this:\n\n```text\nmessage: \"request failed: server error: user 'bob' is not authorized\"\nrpcMsgid: \u003cunique identifier for this request\u003e\nrpcMethod: GetObject\nrpcUser: \"bob\"\n```\n\nTaking this apart:\n\n* The error's message is a complete description of the problem. The caller can\n  report this directly to its caller, which can potentially make its way back to\n  an end user (if appropriate). It can also be logged.\n* The caller can tell that the request failed on the server, rather than as a\n  result of a client problem (e.g., failure to serialize the request), a\n  transport problem (e.g., failure to connect to the server), or something else\n  (e.g., a timeout). They do this using `findCauseByName('FastServerError')`\n  rather than checking the `name` field directly.\n* If the caller logs this error, the logs can be analyzed to aggregate\n  errors by cause, by RPC method name, by user, or whatever. Or the\n  error can be correlated with other events for the same rpcMsgid.\n* It wasn't very hard for any part of the code to contribute to this error.\n  Each part of the stack has just a few lines to provide exactly what it knows,\n  with very little boilerplate.\n\nIt's not expected that you'd use these complex forms all the time. Despite\nsupporting the complex case above, you can still just do:\n\n```ts\nnew ChainError(`my service isn't working`);\n```\n\nfor the simple cases.\n\n\n# API\n\n## Constructor\n\nThe `ChainError` constructor:\n\n```ts\nconstructor(message?: string, optsOrError?: ChainErrorOptions | Error, skipCauseMessage?: boolean);\n```\n\nWhere `ChainErrorOptions` is a plain object with any of the following\noptional properties:\n\n```ts\ninterface ChainErrorOptions {\n  /**\n   * Describes what kind of error this is. This is intended for programmatic use\n   * to distinguish between different kinds of errors. Note that in modern versions of Node.js,\n   * this name is ignored in the `stack` property value, but callers can still use the `name`\n   * property to get at it.\n   */\n  name?: string;\n  /**\n   * Indicates that the new error was caused by `cause`. See `getCause()` below.\n   * If unspecified, the cause will be `null`.\n   */\n  cause?: Error;\n  /**\n   * If specified, then the stack trace for this error ends at function `constructorOpt`.\n   * Functions called by `constructorOpt` will not show up in the stack.\n   * This is useful when this class is subclassed.\n   */\n  constructorOpt?: (...args: any[]) =\u003e any;\n  /**\n   * Specifies arbitrary informational properties that\n   * are available through the `ChainError.getInfo(err)` static class method.\n   * See that method for details.\n   */\n  info?: { [key: string]: any };\n}\n```\n\n## Public properties\n\n`ChainError` provide the public properties as JavaScript's built-in `Error` objects.\n\nProperty name | Type   | Meaning\n------------- | ------ | -------\n`name`  | string | Programmatically-usable name of the error.\n`message`   | string | Human-readable summary of the failure. Programmatically-accessible details are provided through `ChainError.getInfo(err)` class method.\n`stack`   | string | Human-readable stack trace where the Error was constructed.\n\nThe `stack` property is managed entirely by the underlying JavaScript\nimplementation. It's generally implemented using a getter function because\nconstructing the human-readable stack trace is somewhat expensive.\n\n## Class methods\n\nThe following static methods are defined on the `ChainError` class.\n\n```ts\nclass ChainError extends Error {\n  /**\n   * Returns the next `Error` in the cause chain for given `err`,\n   * or `null` if there is no next `ChainError`. See the `cause`\n   * argument to the constructor. Errors can have arbitrarily long cause chains.\n   * You can walk the `cause` chain by invoking `ChainError.getCause(err)`\n   * on each subsequent return value.\n   */\n  static getCause(err: Error): Error | null;\n\n  /**\n   * Returns an object with all of the extra error information that's been associated\n   * with this `Error` and all of its causes. These are the properties passed in using\n   * the `info` option to the constructor. Properties not specified in the\n   * constructor for this `Error` are implicitly inherited from this error's cause.\n   *\n   * These properties are intended to provide programmatically-accessible metadata\n   * about the error. For an error that indicates a failure to resolve a DNS name,\n   * informational properties might include the DNS name to be resolved, or even the\n   * list of resolvers used to resolve it. The values of these properties should\n   * generally be plain objects (i.e., consisting only of `null`, `undefined`, `numbers`,\n   * `booleans`, `strings`, `objects` and arrays containing only other plain objects).\n   */\n  static getInfo(err: Error): ObjectAny;\n\n  /**\n   * Returns a string containing the full stack trace, with all nested errors recursively\n   * reported as `'caused by:' + err.stack`.\n   */\n  static getFullStack(err: Error): string;\n\n  /**\n   * The `findCauseByName()` method traverses the cause chain for given `err`, looking\n   * for an error whose `name` property matches the passed in `name` value. If no\n   * match is found, `null` is returned.\n   *\n   * If all you want is to know _whether_ there's a cause (and you don't care what it is),\n   * you can use `ChainError.hasCauseWithName(err, name)`.\n   *\n   * If a vanilla error or a non-ChainError error is passed in, then there is no cause\n   * chain to traverse. In this scenario, the method will check the `name`\n   * property of only `err`.\n   */\n  static findCauseByName(err: Error, name: string): Error | null;\n\n  /**\n   * Returns `true` if and only if `ChainError.findCauseByName(err, name)` would return\n   * a non-null value. This essentially determines whether `err` has any cause in\n   * its cause chain that has name `name`.\n   */\n  static hasCauseWithName(err: Error, name: string): boolean;\n}\n```\n\n## Examples\n\nMore examples:\n\n```ts\nconst err1 = new ChainError('something bad happened');\n/* ... */\nconst err2 = new ChainError(\n  'failed to connect to \"127.0.0.1:215\"',\n  {\n    name: 'ConnectionError',\n    cause: err1,\n    info: {\n      errno: 'ECONNREFUSED',\n      remote_ip: '127.0.0.1',\n      port: 215\n    }\n  }\n);\n\nconsole.log(err2.message);\nconsole.log(err2.name);\nconsole.log(ChainError.getInfo(err2));\nconsole.log(err2.stack);\n```\n\nThis outputs:\n\n```text\nfailed to connect to \"127.0.0.1:215\": something bad happened\nConnectionError\n{ errno: 'ECONNREFUSED', remote_ip: '127.0.0.1', port: 215 }\nConnectionError: failed to connect to \"127.0.0.1:215\": something bad happened\n  at Object.\u003canonymous\u003e (/home/dap/node-chain-error/examples/info.js:5:12)\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:935:3\n```\n\nInformation properties are inherited up the cause chain, with values at the top\nof the chain overriding same-named values lower in the chain. To continue that\nexample:\n\n```ts\nconst err3 = new ChainError(\n  'request failed',\n  {\n    name: 'RequestError',\n    cause: err2,\n    info: { errno: 'EBADREQUEST' }\n  }\n);\n\nconsole.log(err3.message);\nconsole.log(err3.name);\nconsole.log(ChainError.getInfo(err3));\nconsole.log(err3.stack);\n```\n\nThis outputs:\n\n```text\nrequest failed: failed to connect to \"127.0.0.1:215\": something bad happened\nRequestError\n{ errno: 'EBADREQUEST', remote_ip: '127.0.0.1', port: 215 }\nRequestError: request failed: failed to connect to \"127.0.0.1:215\": something bad happened\n  at Object.\u003canonymous\u003e (/home/dap/node-chain-error/examples/info.js:20:12)\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:935:3\n```\n\nYou can also print the complete stack trace of combined `Error`s by using\n`ChainError.getFullStack(err).`\n\n```ts\nconst err1 = new ChainError('something bad happened');\n/* ... */\nconst err2 = new ChainError('something really bad happened here', err1);\n\nconsole.log(ChainError.getFullStack(err2));\n```\n\nThis outputs:\n\n```text\nChainError: something really bad happened here: something bad happened\n  at Object.\u003canonymous\u003e (/home/dap/node-chain-error/examples/getFullStack.js:5:12)\n  at Module._compile (module.js:409:26)\n  at Object.Module._extensions..js (module.js:416:10)\n  at Module.load (module.js:343:32)\n  at Function.Module._load (module.js:300:12)\n  at Function.Module.runMain (module.js:441:10)\n  at startup (node.js:139:18)\n  at node.js:968:3\ncaused by: ChainError: something bad happened\n  at Object.\u003canonymous\u003e (/home/dap/node-chain-error/examples/getFullStack.js:3:12)\n  at Module._compile (module.js:409:26)\n  at Object.Module._extensions..js (module.js:416:10)\n  at Module.load (module.js:343:32)\n  at Function.Module._load (module.js:300:12)\n  at Function.Module.runMain (module.js:441:10)\n  at startup (node.js:139:18)\n  at node.js:968:3\n```\n\n`ChainError.getFullStack(err)` is also safe to use on regular `Error`s, so feel free to use\nit whenever you need to extract the stack trace from an `Error`, regardless if\nit's a `ChainError` or not.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fts-stack%2Fchain-error","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fts-stack%2Fchain-error","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fts-stack%2Fchain-error/lists"}