Openstatus
www.openstatus.dev
1import type { ErrorCode } from "./error-code";
2
3type ErrorContext = Record<string, unknown>;
4
5export abstract class BaseError<
6 TContext extends ErrorContext = ErrorContext,
7> extends Error {
8 public abstract readonly name: string;
9 /**
10 * A distinct code for the error type used to differentiate between different types of errors.
11 * Used to build the URL for the error documentation.
12 * @example 'UNAUTHENTICATED' | 'INTERNAL_SERVER_ERROR'
13 */
14 public abstract readonly code?: ErrorCode;
15 public readonly cause?: BaseError;
16 /**
17 * Additional context to help understand the error.
18 * @example { url: 'https://example.com/api', method: 'GET', statusCode: 401 }
19 */
20 public readonly context?: TContext;
21
22 constructor(opts: {
23 message: string;
24 cause?: BaseError;
25 context?: TContext;
26 }) {
27 super(opts.message);
28 this.cause = opts.cause;
29 this.context = opts.context;
30
31 // TODO: add logger here!
32 }
33
34 public toString(): string {
35 return `${this.name}(${this.code}): ${
36 this.message
37 } - caused by ${this.cause?.toString()} - with context ${JSON.stringify(
38 this.context,
39 )}`;
40 }
41
42 // get docs(): string {
43 // if (!this.code) return "https://example.com/docs/errors"
44 // return `https://example.com/docs/errors/${this.code}`;
45 // }
46}