What is ts-custom-error?
The ts-custom-error package is a TypeScript library that simplifies the creation of custom error classes. It provides a base class that can be extended to create custom error types with minimal boilerplate code.
What are ts-custom-error's main functionalities?
Creating Custom Error Classes
This feature allows you to create custom error classes by extending the CustomError base class provided by ts-custom-error. The example demonstrates how to create a custom error class named MyCustomError and throw an instance of it.
class MyCustomError extends CustomError {
constructor(message: string) {
super(message);
this.name = 'MyCustomError';
}
}
try {
throw new MyCustomError('Something went wrong!');
} catch (error) {
console.error(error.name); // MyCustomError
console.error(error.message); // Something went wrong!
}
Preserving Stack Trace
This feature ensures that the stack trace is preserved when custom errors are thrown. The example shows how the stack trace includes the function where the error was thrown, which aids in debugging.
class AnotherCustomError extends CustomError {
constructor(message: string) {
super(message);
this.name = 'AnotherCustomError';
}
}
function problematicFunction() {
throw new AnotherCustomError('An error occurred in problematicFunction');
}
try {
problematicFunction();
} catch (error) {
console.error(error.stack); // Stack trace includes problematicFunction
}
Other packages similar to ts-custom-error
custom-error-generator
The custom-error-generator package provides a way to create custom error classes with additional properties and methods. It is similar to ts-custom-error but offers more flexibility in defining custom error properties.
extendable-error-class
The extendable-error-class package allows for the creation of custom error classes with extended functionality. It is similar to ts-custom-error but focuses on providing a more comprehensive base class for error handling.
error-subclass
The error-subclass package is a lightweight library for creating custom error subclasses. It is similar to ts-custom-error but is more minimalistic and focuses on simplicity.
Typescript Custom Error
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 easyly 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 cutom methods, see examples
Use customErrorFactory
factory
Custom error contructor returned by the factory pass the same unit tests.
Factory still allows custom logic inside constructor:
import { customErrorFactory } from 'ts-custom-error'
const HttpError = customErrorFactory(function (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
import { customErrorFactory } from 'ts-custom-error'
const ValidationError = customErrorFactory(function (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
--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()
this.name = 'MyError'
}
}
import { customErrorFactory } from 'ts-custom-error'
const MyError = customErrorFactory(function MyError () {
this.name = 'MyError'
})
Usefull development commands
- Watch source changes and run corresponding unit tests
npm start
npm test
npm run coverage
- Format staged code and run commitizen (enforce commit message convention)
npm run commit
Automate all the things
This project is a playground for various external services and tools, it use:
Similar packages
- custom-error provides a factory with custom name and parent error
- 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 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
- extendable-error-class provides simple class
- extend-error provides a factory attached to global Error object, allows custom name, code & message error
- error-extend provides a factory with custom name, default code & message properties, an optional init function allow more custom properties/methods