import { AxiosError } from "axios"; import { GraphQLServerError } from "./graphql/types.js"; import { HTTPError } from "../../utils/http-client.js"; /** * Represents GraphQL specific errors (validation, missing fields, etc.) */ export class GraphQLError extends Error { constructor( message: string, public errors: GraphQLServerError[] ) { super(message); this.name = "GraphQLError"; } } /** * Centralized error handling for API requests. * Transforms various error types into standardized HTTPError or GraphQLError. */ export class ErrorHandler { /** * Transforms any error into a standardized HTTPError or GraphQLError and throws it. * Never returns - always throws an error. * * @throws {HTTPError|GraphQLError} Standardized error with appropriate details */ static handle(error: unknown): never { if (error instanceof GraphQLError) { throw error; } // Handle HTTPError (already processed by http-client) if (error instanceof HTTPError) { // For GraphQL responses with errors in the data if ( error.data && typeof error.data === "object" && "errors" in error.data && Array.isArray((error.data as any).errors) && (error.data as any).errors.length > 0 ) { const graphqlError = new GraphQLError( "GraphQL Error", (error.data as { errors: GraphQLServerError[] }).errors ); throw graphqlError; } throw error; // Re-throw the original HTTPError } // Handle raw AxiosError (direct usage, not through http-client) if (error instanceof AxiosError) { // For GraphQL responses with errors if ( error.response?.data?.errors && Array.isArray(error.response.data.errors) && error.response.data.errors.length > 0 ) { const graphqlError = new GraphQLError( "GraphQL Error", error.response.data.errors as GraphQLServerError[] ); throw graphqlError; } // For HTTP errors - create HTTPError and log with response data const httpError = new HTTPError( error.message, error.response?.status || 500, error.code, error.response?.data ); throw httpError; } // For other errors const httpError = new HTTPError( error instanceof Error ? error.message : "An unknown error occurred", 500 ); throw httpError; } }