From 4c795cc386a37d559b4ea1035ccaaeec4ead5103 Mon Sep 17 00:00:00 2001 From: wiktormazur Date: Fri, 4 Apr 2025 11:22:43 +0200 Subject: [PATCH] feat: expose error status code --- src/functions/post_fetch_processing.ts | 19 ++++++++----------- src/types/errors.ts | 12 ++++++++++++ 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/functions/post_fetch_processing.ts b/src/functions/post_fetch_processing.ts index 23669430..b1555268 100644 --- a/src/functions/post_fetch_processing.ts +++ b/src/functions/post_fetch_processing.ts @@ -43,19 +43,16 @@ export async function throwErrorIfNotOK(response: Response | undefined) { const errorMessage = `got status: ${status} ${statusText}. ${JSON.stringify( errorBody )}`; + const apiError = new GoogleApiError( + errorBody.error.message, + errorBody.error.code, + errorBody.error.status, + errorBody.error.details + ); if (status >= 400 && status < 500) { - const error = new ClientError( - errorMessage, - new GoogleApiError( - errorBody.error.message, - errorBody.error.code, - errorBody.error.status, - errorBody.error.details - ) - ); - throw error; + throw new ClientError(errorMessage, apiError); } - throw new GoogleGenerativeAIError(errorMessage); + throw new GoogleGenerativeAIError(errorMessage, apiError); } } diff --git a/src/types/errors.ts b/src/types/errors.ts index 4b9b5ba0..36e510e2 100644 --- a/src/types/errors.ts +++ b/src/types/errors.ts @@ -34,11 +34,17 @@ class GoogleAuthError extends Error { */ class ClientError extends Error { public readonly stackTrace?: Error; + public readonly statusCode?: number; + constructor(message: string, stackTrace?: Error) { super(message, {cause: stackTrace}); this.message = constructErrorMessage('ClientError', message); this.name = 'ClientError'; this.stackTrace = stackTrace; + + if (stackTrace instanceof GoogleApiError) { + this.statusCode = stackTrace.code; + } } } @@ -76,11 +82,17 @@ class GoogleApiError extends Error { */ class GoogleGenerativeAIError extends Error { public readonly stackTrace?: Error; + public readonly statusCode?: number; + constructor(message: string, stackTrace?: Error) { super(message, {cause: stackTrace}); this.message = constructErrorMessage('GoogleGenerativeAIError', message); this.name = 'GoogleGenerativeAIError'; this.stackTrace = stackTrace; + + if (stackTrace instanceof GoogleApiError) { + this.statusCode = stackTrace.code; + } } }