Created
May 12, 2021 13:56
-
-
Save dguo/acdfdc87ee4fc500af23091f2fff31da to your computer and use it in GitHub Desktop.
blog - How to Fix instanceof Not Working For Custom Errors in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DatabaseError extends Error {} | |
const error = new DatabaseError("Unique constraint violation"); | |
// prints "true" | |
console.log(error instanceof Error); | |
// incorrectly prints "false" | |
console.log(error instanceof DatabaseError); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DatabaseError extends Error {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DatabaseError extends Error { | |
constructor(message: string) { | |
super(message); | |
Object.setPrototypeOf(this, DatabaseError.prototype); | |
} | |
} | |
const error = new DatabaseError("Unique constraint violation"); | |
// both print "true" now | |
console.log(error instanceof Error); | |
console.log(error instanceof DatabaseError); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DatabaseError extends Error { | |
constructor(message: string) { | |
super(message); | |
Object.setPrototypeOf(this, DatabaseError.prototype); | |
} | |
} | |
class DatabaseConnectionError extends DatabaseError { | |
constructor(message: string) { | |
super(message); | |
Object.setPrototypeOf(this, DatabaseConnectionError.prototype); | |
} | |
} | |
const error = new DatabaseConnectionError("Invalid credentials"); | |
// all print "true" | |
console.log(error instanceof Error); | |
console.log(error instanceof DatabaseError); | |
console.log(error instanceof DatabaseConnectionError); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment