Skip to content

Instantly share code, notes, and snippets.

@spruce-bruce
Created November 5, 2022 23:49
Show Gist options
  • Save spruce-bruce/31d22f751672bfadd06ed2215f369519 to your computer and use it in GitHub Desktop.
Save spruce-bruce/31d22f751672bfadd06ed2215f369519 to your computer and use it in GitHub Desktop.
Custom errors in typescript
/**
 * 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;
    }
  }
}
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