0

Im working at big project using TypeScript. Now I create error classes using standard Error class as superclass. But there are lots of similar code in every derived class:

class AddonError extends Error {
    constructor(message:string) {
        super(message);

        this.message = message;
        this.stack = (new Error()).stack;
    }

    readonly message:string;
    readonly stack:string|undefined;
}

Is it right way to create error superclass with this code? I doubt because of extending and one more import directive...

B. Bohdan
  • 480
  • 4
  • 12
  • 1
    Why do you explicitly repeat the stuff that `super(message)` already does for you? Your code can be simplified to `class AddonError extends Error {}` – Bergi Sep 21 '18 at 10:17
  • As I know there are some problems with standard `Error` class. Extending do not lead to writing error data like message and stack to derived class. https://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript Correct me if i'm not right. – B. Bohdan Sep 21 '18 at 10:22
  • 1
    Related: https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work – k0pernikus Sep 21 '18 at 10:23
  • 1
    @B.Bohdan None of the answers in the linked question are doing what you are doing. Those that assign `message`, `name` and `stack` properties define a `UserError` that you should extend as `class AddonError extends Error {}`. And no, the problems with extending ES5 `Error` should be solved by using the respective transpiler plugin, instead of having to do it manually in your code. – Bergi Sep 21 '18 at 12:03

0 Answers0