Typescript - Extending Error class

前端 未结 6 945
一向
一向 2020-11-27 03:07

I\'m trying to throw a custom error with my \"CustomError\" class name printed in the console instead of \"Error\", with no success:

class CustomError extend         


        
6条回答
  •  离开以前
    2020-11-27 03:39

    I ran into the same problem in my typescript project a few days ago. To make it work, I use the implementation from MDN using only vanilla js. So your error would look something like the following:

    function CustomError(message) {
      this.name = 'CustomError';
      this.message = message || 'Default Message';
      this.stack = (new Error()).stack;
    }
    CustomError.prototype = Object.create(Error.prototype);
    CustomError.prototype.constructor = CustomError;
    
    throw new CustomError('foo');

    It doesn't seem to work in SO code snippet, but it does in the chrome console and in my typescript project:

提交回复
热议问题