UNPKG

bigblocks

Version:

Complete Bitcoin UI component library - authentication, social, wallet, market, inscriptions, and blockchain interactions for React

113 lines (112 loc) 3.23 kB
/** * Standardized API Error class that implements SocialError interface * while extending native Error for proper stack traces and instanceof checks */ export class ApiError extends Error { code; details; constructor(code, message, details) { super(message); this.name = "ApiError"; this.code = code; this.details = details; // Ensure proper prototype chain for instanceof checks Object.setPrototypeOf(this, ApiError.prototype); // Capture stack trace if available (V8 engines like Chrome/Node.js) if (Error.captureStackTrace) { Error.captureStackTrace(this, ApiError.prototype.constructor); } } /** * Convert a generic error to an ApiError */ static fromError(error, code = "UNKNOWN_ERROR") { if (error instanceof ApiError) { return error; } if (error instanceof Error) { return new ApiError(code, error.message, error); } if (typeof error === "string") { return new ApiError(code, error); } return new ApiError(code, "An unknown error occurred", { originalError: error, }); } /** * Create a network error for fetch failures */ static networkError(message, details) { return new ApiError("NETWORK_ERROR", message, details); } /** * Create an unauthorized error */ static unauthorized(message = "User must be authenticated") { return new ApiError("UNAUTHORIZED", message); } /** * Create a transaction failed error */ static transactionFailed(message, details) { return new ApiError("TRANSACTION_FAILED", message, details); } /** * Create a broadcast failed error */ static broadcastFailed(message, details) { return new ApiError("BROADCAST_FAILED", message, details); } /** * Check if an error is an API error with a specific code */ static isApiError(error, code) { if (!(error instanceof ApiError)) { return false; } return code ? error.code === code : true; } /** * Serialize the error for logging or transmission */ toJSON() { return { name: this.name, code: this.code, message: this.message, details: this.details, stack: this.stack, }; } /** * Convert to SocialError interface (for compatibility) */ toSocialError() { return { code: this.code, message: this.message, details: this.details, }; } } /** * Type guard to check if an error implements SocialError interface */ export function isSocialError(error) { return (typeof error === "object" && error !== null && "code" in error && "message" in error && typeof error.code === "string" && typeof error.message === "string"); } /** * Convert any error to a standardized SocialError */ export function toSocialError(error) { if (isSocialError(error)) { return error; } return ApiError.fromError(error).toSocialError(); }