Created
November 5, 2022 23:49
-
-
Save spruce-bruce/31d22f751672bfadd06ed2215f369519 to your computer and use it in GitHub Desktop.
Custom errors in typescript
This file contains hidden or 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
/** | |
* This CustomError type can safely be extened and your custom errors | |
* will show up nicely in logs and anywhere else for that matter. | |
* | |
* Javascript errors break the prototype chain so if you want nice | |
* errors that you can extend you need to do some work to restore it. | |
* | |
* shamelessly stolen from https://stackoverflow.com/a/48342359 | |
*****************/ | |
export abstract class CustomError extends Error { | |
constructor(message?: string) { | |
// 'Error' breaks prototype chain here | |
super(message); | |
// restore prototype chain | |
const actualProto = new.target.prototype; | |
if (Object.setPrototypeOf) { | |
Object.setPrototypeOf(this, actualProto); | |
} else { | |
(this as any).__proto__ = actualProto; | |
} | |
} | |
} |
This file contains hidden or 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
import { CustomError } from './CustomError'; | |
import { isError } from 'lodash'; | |
export class DomainInvariantViolation extends CustomError { | |
name: 'DomainInvariantViolation'; | |
constructor(message: string) { | |
super(message); | |
this.name = 'DomainInvariantViolation'; | |
} | |
} | |
export const isDomainInvariantViolation = ( | |
e: any, | |
): e is DomainInvariantViolation => | |
isError(e) && e.name === 'DomainInvariantViolation'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment