Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ts-custom-error

adriengibrat2mMIT3.3.1TypeScript support: included

Extend native Error to create custom errors

custom Error, extend, Error

readme

Typescript Custom Error

NPM version Pet project License: MIT Build Status BCH compliance CodeQL Maintainability Test Coverage Commitizen friendly Install size Bundle size

Extend native Error to create custom errors

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.

Why

Because extending native Error in node and in browsers is tricky

class MyError extends Error {
    constructor(m) {
        super(m)
    }
}

doesn't work as expected in ES6 and is broken in Typescript.

Use CustomError class

Simply extends and call super in you custom constructor.

import { CustomError } from 'ts-custom-error'

class HttpError extends CustomError {
    public constructor(
        public code: number,
        message?: string,
    ) {
        super(message)
    }
}

...

new HttpError(404, 'Not found')

You may want more advanced contructor logic and custom methods, see examples

Use customErrorFactory factory

Custom error contructor returned by the factory pass the same unit tests as Class constructor.

Factory still allows custom logic inside constructor:

import { customErrorFactory } from 'ts-custom-error'

const HttpError = customErrorFactory(function HttpError (code: number, message= '') {
    this.code = code
    this.message = message
})

...

new HttpError(404, 'Not found')

Custom Error from customErrorFactory can:

  • Be called as a simple function
    HttpError(404, 'Not found')
  • Extend any native Error, using the second optional argument `ts import { customErrorFactory } from 'ts-custom-error'

const ValidationError = customErrorFactory(function ValidationError (message= 'Invalid parameter') { this.message = message }, TypeError)


### Known limitations

#### 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](https://github.com/mishoo/UglifyJS2/blob/harmony/README.md) `--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:

```ts
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:

Licence

Starting version 3.0.0 this project is under MIT licence, there are no code change between version 2.2.2 and version 3.0.0 but changing licence was considered as a breaking change. All versions < 3.0.0 are under WTFPL.

Similar packages

  • custom-error custom-error provides a factory with custom name and parent error
  • custom-errors custom-errors provides a class and a factory with custom name and message, easy integration with with express and (log)[https://github.com/visionmedia/log.js]
  • custom-error-generator custom-error-generator provides a factory with custom name, default properties and a constructor (node only)
  • custom-error-instance custom-error-instance provides a factory with custom name, properties and construction logic (! browser compatibility: redefine constructor name)
  • node-custom-errors 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 extendable-error provides a class with clean stacktrace even in non v8 environments
  • extendable-error-class extendable-error-class provides simple class
  • extend-error extend-error provides a factory attached to global Error object, allows custom name, code & message error
  • error-extend error-extend provides a factory with custom name, default code & message properties, an optional init function allow more custom properties/methods

changelog

3.3.1 (2022-11-01)

Bug Fixes

  • avoid error Cannot find name 'ErrorOptions' (7535f79)

3.3.0 (2022-10-22)

Bug Fixes

  • add es2022 typescript lib (e04a6b1)

Features

  • cause: add suport for error cause (683cf2b)

3.2.2 (2022-08-27)

Bug Fixes

  • build badge & publish semantic release branch (b44245c)
  • publish new release (436918e)
  • renamed branch to main & updated all dev deps / CI (7733299)

3.2.1 (2022-08-27)

Bug Fixes

  • update types to support TS 4.8.2 (80f5eb0)

3.2.0 (2020-08-24)

Features

  • name: Allow to redefine error name property (94efde0)

3.1.1 (2019-07-03)

Bug Fixes

  • package: Remove codeclimate-reporter binary from npm package (52a6db9), closes #32

3.1.0 (2019-05-17)

Features

  • log: Behave like native Error when using console.log (f884c51), closes #30

3.0.0 (2019-03-15)

chore

  • licence: Change licence to MIT instead of WTFPL (7ff194c), closes #27

BREAKING CHANGES

  • licence: Change licence to MIT!

2.2.2 (2018-12-29)

Bug Fixes

  • release: Fix umd minification issue, add typescript definitions for all bundles formats (a091837)

2.2.1 (2018-04-04)

Bug Fixes

  • Fix latest travis deploy fail status (0b18352)

2.2.0 (2018-04-04)

Features

  • Add custom error name support (7791153)

2.1.0 (2018-03-24)

Features

  • Improve factory typings (dc1eed6)

2.0.0 (2018-03-16)

Code Refactoring

  • Change factory export name to customErrorFactory (e8f51a0)

Features

  • Export factory Typescript Interfaces (d03b476)

BREAKING CHANGES

  • the factory export name changed from factoryto more expliit customErrorFactory

1.0.1 (2018-03-12)

Bug Fixes

  • Expose constructor in prototype when using factory (387cc8d)

1.0.0 (2018-03-12)

Code Refactoring

  • Rewrite factory to be Higher order function (720940c)

BREAKING CHANGES

  • The factory now accept a function as first parameter where previously it used an error name and a list of property keys

0.0.2 (2018-03-12)

First release