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
CustomError
class allow to easyly extends native Error in Typescript
Using a class
import { CustomError } from 'ts-custom-error'
class HttpError extends CustomError {
public constructor(
public code: number,
message?: string,
) {
super(message)
}
}
...
new HttpError(404, 'Not found')
More advanced examples
Using a factory
import { customErrorFactory } from 'ts-custom-error'
const HttpError = customErrorFactory(function (code, message= '') {
this.code = code
this.message = message
})
...
new HttpError(404, 'Not found')
HttpError(404, 'Not found')
Factory still allows custom logic inside constructor
They pass the same unit tests, the difference is that constructor can be called as a simple function
Similar packages