0

I have the following code:

export class PutTimeEntryValidationError extends Error {
  constructor(message: string, public errors: PutTimeEntryError[]) {
    super(message);
  }
}

try {
   throw new PutTimeEntryValidationError("test",[]);
} catch(ex){
   if (ex instanceof PutTimeEntryValidationError){
      debugger; // 
   } else {
      debugger; // code stops here somehow
   } 
}

Im using webpack 3 with awesome typescript loader and this tsconfig.js:

{
    "compilerOptions": {
        "outDir": "./wwwroot/js/", // path to output directory
        "sourceMap": true, // allow sourcemap support
        "noImplicitAny": false, 
        "strictNullChecks": true, // enable strict null checks as a best practice
        "module": "commonjs", // specifiy module code generation
        "jsx": "react",             // use typescript to transpile jsx to js
        "target": "es5", // specify ECMAScript target version
        "allowJs": true, // allow a partial TypeScript and JavaScript codebase
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [
            "es2015", 
            "es5", //needed for hmr
            "es6",
            "dom"
        ],
        "noUnusedLocals": false
    },
    "include": [
        "./react/**/*"
    ]
}

and:

  "typescript": "^2.4.1",

how come my error is not actually a subclass of Error?

// _1 is compiled suffix
ex_1 instanceof Error //true
ex_1.__proto__ // name: Error
1

1 Answer 1

1

For those coming here.

I fond this was the solution:

export class PutTimeEntryValidationError extends Error {
    constructor(message: string, public errors: PutTimeEntryError[]) {
        super(message);

        // Fix prototype:
        Object.setPrototypeOf(this, PutTimeEntryValidationError.prototype);
    }
}

apparently transpiling to es5 breaks this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.