@nevware21/ts-utils
    Preparing search index...

    Function createCustomError

    • Create a Custom Error class which may be used to throw custom errors.

      Type Parameters

      Parameters

      • name: string

        The name of the Custom Error

      • OptionalconstructCb: (self: any, args: IArguments) => void

        [Optional] An optional callback function to call when a new Customer Error instance is being created.

      • OptionalerrorBase: B

        [Optional] (since v0.9.6) The error class to extend for this class, defaults to Error.

      Returns T

      A new Error class

      import { createCustomError, isError } from "@nevware21/ts-utils";

      // For an error that just contains a message
      let myCustomErrorError = createCustomError("MessageError");

      try {
      throw new myCustomErrorError("Error Message!");
      } catch(e) {
      // e.name === MessageError
      // isError(e) === true;
      // Object.prototype.toString.call(e) === "[object Error]";
      }

      // Or a more complex error object
      interface MyCriticalErrorConstructor extends CustomErrorConstructor {
      new(message: string, file: string, line: number, col: number): MyCriticalError;
      (message: string, file: string, line: number, col: number): MyCriticalError;
      }

      interface MyCriticalError extends Error {
      readonly errorId: number;
      readonly args: any[]; // Holds all of the arguments passed during construction
      }

      let _totalErrors = 0;
      let myCustomError = createCustomError<MyCriticalErrorConstructor>("CriticalError", (self, args) => {
      _totalErrors++;
      self.errorId = _totalErrors;
      self.args = args;
      });

      try {
      throw new myCustomError("Not Again!");
      } catch(e) {
      // e.name === CriticalError
      // isError(e) === true;
      // Object.prototype.toString.call(e) === "[object Error]";
      }

      // ----------------------------------------------------------
      // Extending another custom error class
      // ----------------------------------------------------------

      let AppError = createCustomError("ApplicationError");
      let theAppError = new appError();

      isError(theAppError); // true
      theAppError instanceof Error; // true
      theAppError instanceof AppError; // true

      let StartupError = createCustomError("StartupError", null, AppError);
      let theStartupError = new StartupError();

      isError(theStartupError); // true
      theStartupError instanceof Error; // true
      theStartupError instanceof AppError; // true
      theStartupError instanceof StartupError; // true