Typescript chained error
Highlights
- Allows stacking errors with "Caused by: " keyword in stack
- Preserves error class name in trace (uses ts-custom-error for that)
- Automatically cleans up stack using clean-stack](https://github.com/sindresorhus/clean-stack)
- Has a
ChainedErrorFactory
that can extend any already existing error withCaused by
clause additional properties and - 100% test coverage. Used in healthcare-grade solutions
Installation
$ npm install --save typescript-chained-error
Usage
- Define custom error class with a constructor that has a cause as a second parameter
- Throw your custom error passing the causing error as a second parameter
- Error causes can be stacked (there may be many causes that are finally leading to the printed error)
; // function that may throw // call function with illegal parameterbuildArray-5;
The output:
CannotPerformCalculationsError: Cannot build array
at buildArray (/typescript-chained-error/src/test.ts:14:15)
at Object.<anonymous> (/typescript-chained-error/src/test.ts:18:1)
(...)
Caused by: RangeError: Invalid array length
at buildArray (/typescript-chained-error/src/test.ts:12:16)
at Object.<anonymous> (/typescript-chained-error/src/test.ts:18:1)
(...)
Options
// Pass options in constructorpublic constructormsg?: string, cause?: Error
Using ChainedErrorFactory
Example with firebase-functions https error (which is the only error that is thrown at the call site).
;; throw ChainedErrorFactory.make // primary error that will be extended (this error is preserved in the prototype chain): functions.https.HttpsError"resource-exhausted", "Message", // Causing error: new TypeError"Cause error", // (optional) Additional fields that will be assigned to the returned error object // e.g.: functions.https.HttpsError allow to add a details field to the error. That field will be reconstructed at the call site. /* optional: */ , // (optional) Options. Specified above.;
Extends the brilliant ts-custom-error. Uses clean-stack by @sindresorhus for pretty output. | Made with ❤️ by Jędrzej Lewandowski.