@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: (this: any, self: any, args: IArguments, isOwnInstance?: boolean) => void

        [Optional] An optional callback function to call when a new Custom Error instance is being created. (Since v0.16.0) The callback is invoked with this bound to the same instance that is also passed as the self (1st) argument, so implementations may use either this.prop = ... or self.prop = ... interchangeably - this only applies when constructCb is a normal (non-arrow) function, as arrow functions ignore the bound this and keep their own lexically captured value. The 3rd argument, isOwnInstance, is true when this class is the leaf-most (most-derived) type actually being instantiated (eg. new ThisClass()), and false when this class's own constructor is only running because it is a base class of some other custom error further down an inheritance chain (eg. new SomeSubClass(), where SomeSubClass was created via createCustomError(..., ThisClass)). Use this to skip work - such as your own stack-trace capture - that only the leaf-most instance actually needs, since a base class's own construction step runs (and would otherwise redo that work) for every instance of every one of its subclasses too.

      • OptionalerrorBase: B

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

      • OptionalsuperArgsFn: (args: IArguments) => ArrayLike<any>

        [Optional] (since v0.13.0) An optional function that receives the constructor arguments and returns the arguments to pass to the base class constructor. When not provided all constructor arguments are forwarded to the base class. Use this to support a different argument order or to pass a subset of arguments to the base class (similar to calling super(...) in a class).

      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

      // ----------------------------------------------------------
      // Custom error with reordered / transformed arguments
      // (the superArgsFn maps constructor args to base class args)
      // ----------------------------------------------------------

      interface HttpErrorConstructor extends CustomErrorConstructor<HttpError> {
      new(statusCode: number, message: string): HttpError;
      (statusCode: number, message: string): HttpError;
      }

      interface HttpError extends Error {
      readonly statusCode: number;
      }

      // HttpError takes (statusCode, message) but base Error expects (message)
      let MyHttpError = createCustomError<HttpErrorConstructor>("HttpError",
      (self, args) => {
      self.statusCode = args[0];
      },
      Error,
      (args) => [ args[1] ] // pass only the message to base Error constructor
      );

      let err = new MyHttpError(404, "Not Found");
      err.message; // "Not Found"
      err.statusCode; // 404