Custom error class in TypeScript

后端 未结 5 523
别跟我提以往
别跟我提以往 2020-12-02 12:06

I\'d like to create my own error class in TypeScript, extending core Error to provide better error handling and customized reporting. For example, I want to cre

5条回答
  •  执念已碎
    2020-12-02 12:29

    For Typescript 3.7.5 this code provided a custom error class that also captured the correct stack information. Note instanceof does not work so I use name instead

    // based on https://gunargessner.com/subclassing-exception
    
    // example usage
    try {
      throw new DataError('Boom')
    } catch(error) {
      console.log(error.name === 'DataError') // true
      console.log(error instanceof DataError) // false
      console.log(error instanceof Error) // true
    }
    
    class DataError {
      constructor(message: string) {
        const error = Error(message);
    
        // set immutable object properties
        Object.defineProperty(error, 'message', {
          get() {
            return message;
          }
        });
        Object.defineProperty(error, 'name', {
          get() {
            return 'DataError';
          }
        });
        // capture where error occured
        Error.captureStackTrace(error, DataError);
        return error;
      }
    }
    

    There are some other alternatives and a discussion of the reasons.

提交回复
热议问题