UNPKG

@aibtc/types

Version:

TypeScript types for AIBTC

46 lines (45 loc) 1.52 kB
import { ErrorMessages, ErrorStatusCodes } from "./error-catalog"; /** * Standard API error class used throughout the application */ export class ApiError extends Error { code; status; details; id; /** * Create a new API error * * @param code - Error code from the ErrorCode enum * @param details - Optional details to include in the error message * @param id - Optional error ID (generated if not provided) */ constructor(code, details, id) { // Get the message template for this error code let message = ErrorMessages[code]; // Replace placeholders with values from details if (details) { Object.entries(details).forEach(([key, value]) => { message = message.replace(`{${key}}`, String(value)); }); } super(message); this.name = "ApiError"; this.code = code; this.status = ErrorStatusCodes[code]; this.details = details; // Generate or use provided error ID this.id = id || this.generateId(); } /** * Generates a unique error ID */ generateId() { // Use crypto.randomUUID() if available if (typeof crypto !== "undefined" && crypto.randomUUID) { return crypto.randomUUID().split("-")[0]; // Use first segment for brevity } // Fallback to timestamp + random string return Date.now().toString(36) + Math.random().toString(36).substring(2, 5); } }