/** * @module CivilityApiError — structured client-side error * * Parsed from the server's `ErrorResponse`, or constructed directly for * network/timeout errors that occur before a response arrives. */ import { domainOf, type ErrorCode, type ErrorDomain } from './codes.ts' import type { ErrorResponse } from './response.ts' export interface CivilityApiErrorInit { code: ErrorCode message: string httpStatus: number messageKey?: string details?: unknown cause?: unknown } export class CivilityApiError extends Error { readonly code: ErrorCode readonly httpStatus: number /** Stable i18n key for this message variant, when the server sent one. */ readonly messageKey?: string readonly details?: unknown constructor(init: CivilityApiErrorInit) { super(init.message, init.cause !== undefined ? { cause: init.cause } : {}) this.name = 'CivilityApiError' this.code = init.code this.httpStatus = init.httpStatus this.messageKey = init.messageKey this.details = init.details } /** The leading segment of `code`, e.g. `auth`, `sync`, `quota`. */ get domain(): ErrorDomain { return domainOf(this.code) } /** * Build an error from a parsed server `ErrorResponse` body and the * originating HTTP status code. */ static fromResponse( body: ErrorResponse, httpStatus: number, ): CivilityApiError { return new CivilityApiError({ code: body.code, message: body.message, httpStatus, // Non-string messageKey degrades to absent rather than rejecting the envelope. messageKey: typeof body.messageKey === 'string' ? body.messageKey : undefined, details: body.details, }) } }