/** * Application errors as values (template from the `dev` skill): never thrown, returned inside an Either. * `kind` picks the transport status, `code` is stable for the client translation, `message` is English for logs. */ export const ERROR_KINDS = [ 'VALIDATION', 'UNAUTHENTICATED', 'FORBIDDEN', 'NOT_FOUND', 'CONFLICT', 'BUSINESS_RULE', 'RATE_LIMITED', 'EXTERNAL_SERVICE', 'UNEXPECTED', ] as const export type ErrorKind = (typeof ERROR_KINDS)[number] export type ErrorParams = Readonly> export abstract class AppError { abstract readonly kind: ErrorKind constructor( readonly code: Code, readonly message: string, readonly params: ErrorParams = {}, ) {} } export class ValidationError extends AppError { readonly kind = 'VALIDATION' as const constructor(code: Code, message: string, params: ErrorParams = {}, readonly fieldErrors: Readonly> = {}) { super(code, message, params) } } export class UnauthenticatedError extends AppError { readonly kind = 'UNAUTHENTICATED' as const } export class ForbiddenError extends AppError { readonly kind = 'FORBIDDEN' as const } export class NotFoundError extends AppError { readonly kind = 'NOT_FOUND' as const } export class ConflictError extends AppError { readonly kind = 'CONFLICT' as const } export class BusinessRuleError extends AppError { readonly kind = 'BUSINESS_RULE' as const } export class RateLimitedError extends AppError { readonly kind = 'RATE_LIMITED' as const } export class ExternalServiceError extends AppError { readonly kind = 'EXTERNAL_SERVICE' as const } /** A bug: the edge logs it and answers a generic message, never the internals. */ export class UnexpectedError extends AppError<'UNEXPECTED_ERROR'> { readonly kind = 'UNEXPECTED' as const constructor(readonly cause: unknown) { super('UNEXPECTED_ERROR', 'Unexpected error.') } } /** The single status map, used by the transport edge (tRPC / HTTP). */ export const HTTP_STATUS: Readonly> = { VALIDATION: 400, UNAUTHENTICATED: 401, FORBIDDEN: 403, NOT_FOUND: 404, CONFLICT: 409, BUSINESS_RULE: 422, RATE_LIMITED: 429, EXTERNAL_SERVICE: 502, UNEXPECTED: 500, } export const TRPC_CODE: Readonly> = { VALIDATION: 'BAD_REQUEST', UNAUTHENTICATED: 'UNAUTHORIZED', FORBIDDEN: 'FORBIDDEN', NOT_FOUND: 'NOT_FOUND', CONFLICT: 'CONFLICT', BUSINESS_RULE: 'UNPROCESSABLE_CONTENT', RATE_LIMITED: 'TOO_MANY_REQUESTS', EXTERNAL_SERVICE: 'BAD_GATEWAY', UNEXPECTED: 'INTERNAL_SERVER_ERROR', }