简体   繁体   中英

How can I create a subtype of Error to throw it?

I am trying to throw my own kind of error, so that when catching I can call if(instanceof DatabaseError) and handle it my own way.

export class DatabaseError extends Error {
    constructor(...args: string[] | undefined[]) {
        super(...args);
        this.name = "DatabaseError"
    }
}

const err: DatabaseError = new DatabaseError(`Message`);
console.log(Object.getPrototypeOf(err));

However, it looks like for all intents and purposes, err is not an instance of DatabaseError. The log returns Error {} , and instanceof DatabaseError returns false. What have I done wrong, and what is the correct way to introduce new Errors so that I can handle them differenty? Or should I create an object that doesn't inherit from Error?

Here is the tsconfig.json I am using:

{
  "compilerOptions": {
    "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    /* Strict Type-Checking Options */
    "strict": true, /* Enable all strict type-checking options. */
    "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    /* Advanced Options */
    "skipLibCheck": true, /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
  }
}

Are You sure you tried instanceof ?

export class DatabaseError extends Error {
    constructor(...args: string[] | undefined[]) {
        super(...args);
        this.name = "DatabaseError"
    }
}

const err: DatabaseError = new DatabaseError(`Message`);
err instanceof DatabaseError // true

You can try this conde in your console, just don't forget remove type anotations. It works for me as expected.

You don't need to use getPrototypeOf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM