Skip to main content
Module

x/berror/berror.ts

Rich Errors including chain of causes, metadata, easy logging and TypeScript definitions.
Latest
File
export class BError extends Error { private firstStack: string | undefined = undefined
/** * @param msg - A description of the error * @param cause - If you are inside a `catch` block you can pass the caught error here * @param metadata - An object containing any data that could be useful for debugging */ constructor( msg: string, cause?: Error, public metadata?: Record<string, unknown> ) { super(msg) // Workaround for https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work Object.setPrototypeOf(this, BError.prototype)
if (cause != undefined) { const subMessage = cause instanceof Error ? cause.message : `non-error object thrown: ${JSON.stringify(cause)}` this.message = `${this.message}: ${subMessage}`
if (!this.firstStack) { this.firstStack = cause.stack } }
this.stack = this.firstStack
this.metadata = { ...(cause instanceof BError ? cause.metadata : {}), ...metadata }; }
public log(...args: unknown[]) { const noMetadata = !this.metadata || Object.entries(this.metadata).length === 0
if (noMetadata) { console.error(this.message) } else { console.error(this.message, this.metadata) } }}