ts-custom-error

repository·main·Indexed 41 days ago

https://github.com/adriengibrat/ts-custom-error

A lightweight TypeScript package (v3.3.1) for extending the native Error class in Node.js and modern browsers. It provides the CustomError class for class-based errors and the customErrorFactory function for factory-pattern error creation, ensuring proper prototype chains and stack traces while preventing name mangling during minification.

Tokens
1.7K
Snippets
6
Records
8
Agent score
50%

What's inside ts-custom-error

  1. Prevent error name mangling during minification

    main

    Minifiers and transpilers can mangle custom error names, which causes issues in stack traces or when checking error names instead of using instanceof.

    To ensure the error name remains correct, explicitly set the name property using Object.defineProperty in your constructor or factory function.

    // For Class-based errors
    import { CustomError } from 'ts-custom-error'
    
    class MyError extends CustomError {
    	constructor() {
    		super()
    		Object.defineProperty(this, 'name', { value: 'MyError' })
    	}
    }
    
    // For Factory-based errors
    import { customErrorFactory } from 'ts-custom-error'
    
    const MyError = customErrorFactory(function MyError () {
    	Object.defineProperty(this, 'name', { value: 'MyError' })
    })
  2. Create custom errors using the CustomError class

    main

    To create a custom error using class syntax, extend the CustomError class and call super() in your constructor. This approach is useful when you need advanced constructor logic or custom methods on your error instances.

    import { CustomError } from 'ts-custom-error'
    
    class HttpError extends CustomError {
    	public constructor(
    		public code: number,
    		message?: string,
    	) {
    		super(message)
    	}
    }
    
    new HttpError(404, 'Not found')
  3. Create custom errors using the customErrorFactory function

    main

    The customErrorFactory function allows you to create error constructors using a factory pattern. The resulting error can be instantiated with new or called as a simple function.

    Key features:

    • Function invocation: You can call the error as a function (e.g., HttpError(404, 'msg')).
    • Base Error selection: You can specify which native error to extend (e.g., TypeError) as the second optional argument.
    import { customErrorFactory } from 'ts-custom-error'
    
    // Standard factory usage
    const HttpError = customErrorFactory(function HttpError (code: number, message= '') {
    	this.code = code
    	this.message = message
    })
    
    new HttpError(404, 'Not found')
    
    // Extending a specific native error (e.g., TypeError)
    const ValidationError = customErrorFactory(function ValidationError (message= 'Invalid parameter') {
    	this.message = message
    }, TypeError)
  4. Extend the CustomError class to create applicative errors

    main

    To create domain-specific errors in TypeScript, extend the CustomError class. This class handles the complexities of extending the native Error object, such as fixing the prototype chain and ensuring the name property correctly reflects the subclass name without being enumerable.

    When implementing a subclass, you can pass a message and an options object containing a cause (useful for error chaining) to the super() call.

    class HttpError extends CustomError {
    	public constructor(
    		public code: number,
    		message?: string,
         cause?: Error,
    	) {
    		super(message, { cause })
    	}
    }
    
    // Usage
    throw new HttpError(404, 'Not found')
  5. Configure the parent error class in customErrorFactory

    main

    The customErrorFactory function accepts an optional second argument, parent, which must be a GenericErrorConstructor. This allows you to base your custom error on something other than the standard Error class, such as TypeError or RangeError.

    GenericErrorConstructor includes:

    • ErrorConstructor
    • EvalErrorConstructor
    • RangeErrorConstructor
    • ReferenceErrorConstructor
    • SyntaxErrorConstructor
    • TypeErrorConstructor
    • URIErrorConstructor
    • Any CustomErrorConstructor
    // Example: Creating a custom error that inherits from TypeError
    const MyTypeError = customErrorFactory(function (msg: string) {
      this.message = msg;
    }, TypeError);
    
    const err = new MyTypeError('Invalid type');
    console.log(err instanceof TypeError); // true
  6. Create custom errors with customErrorFactory

    main

    Use customErrorFactory to easily extend native error classes (like Error, TypeError, etc.) into custom applicative errors.

    To use it, pass a function that defines the custom properties you want to attach to the error instance. The factory handles the prototype chain, sets the error name based on your function's name, and attempts to clean up the stack trace.

    By default, it extends the native Error class, but you can specify a different parent constructor if needed.

    const HttpError = customErrorFactory(function (code: number, message = '') {
    	this.code = code
    	this.message = message
    })
    
    // You can use it with 'new'
    const error = new HttpError(404, 'Not found');
    console.log(error.code); // 404
    
    // Or call it as a function (the factory handles the 'new' internally)
    const error2 = HttpError(500, 'Internal Server Error');