ts-custom-error is a tiny (~500 bytes of minified & gzipped Javascript) package providing a CustomError class and a customErrorFactory function to easily extends native Error in node and evergreen browsers.
It's written in Typescript and try to offer the best development and debug experiences: bundled in Javascript with Typescript definition files, map files and bundled js files for various environments: transpiled to es5 with commonjs, module and umd exports, the umd bundle is also available minified for easy import in browsers.
Minification and transpilation mangle custom Error names.
Unexpected results are:
Minified identifiers in place of custom Error name in Stacktrace
Wrong error recognition where using errors name (bad practice) instead of instanceof
You may fix this behaviour by:
Using uglifyjs options--mangle 'except=["MyError"]' (need to specify all custom error names) or --keep_fnames / --keep_classnames (nothing to specify but your bundle size will be larger)
Setting explicitly error name:
import { CustomError } from 'ts-custom-error'class MyError extends CustomError { constructor() { super() // Set name explicitly as minification can mangle class names Object.defineProperty(this, 'name', { value: 'MyError' }) }}
import { customErrorFactory } from 'ts-custom-error'const MyError = customErrorFactory(function MyError () { // Set name explicitly as minification can remove function expression names Object.defineProperty(this, 'name', { value: 'MyError' })})
Usefull development commands
Watch source changes and run corresponding unit tests
npm start
Run all unit tests
npm test
Get coverage report
npm run coverage
Format staged code and run commitizen (enforce commit message convention)
npm run commit
Automate all the things
⚠️ This project is mainly a pet project and its first purpose is to be a playground for various external services and tools:
opinionated code style mostly inspired from standardjs
custom-error-generator provides a factory with custom name, default properties and a constructor (node only)
custom-error-instance provides a factory with custom name, properties and construction logic (! browser compatibility: redefine constructor name)
node-custom-errors provides factories to create abstract or concrete error with default message, an optional constructor function allow more custom properties/methods (node/chrome only, because no feature detection)
extendable-error provides a class with clean stacktrace even in non v8 environments