From 37fe8eb685cbb1117ae0ca45457f042bfeb3b550 Mon Sep 17 00:00:00 2001 From: Naoki Ainoya Date: Wed, 2 Jul 2025 09:18:50 +0900 Subject: [PATCH] fix: improve error handling for AI service responses - Add defensive check for response.body existence to prevent undefined property access - Include x-ms-error-code header in error messages for better debugging - Provide clearer error messages for different failure scenarios - Fix 'Cannot read properties of undefined (reading 'error')' runtime error This improves the debugging experience when AI service requests fail due to network issues, authentication errors, or unexpected response formats. --- src/main.ts | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/main.ts b/src/main.ts index 9bf26f7..cc38567 100644 --- a/src/main.ts +++ b/src/main.ts @@ -82,14 +82,27 @@ export async function run(): Promise { }) if (isUnexpected(response)) { - if (response.body.error) { + // Extract x-ms-error-code from headers if available + const errorCode = response.headers['x-ms-error-code'] + const errorCodeMsg = errorCode ? ` (error code: ${errorCode})` : '' + + // Check if response body exists and contains error details + if (response.body && response.body.error) { throw response.body.error } + + // Handle case where response body is missing + if (!response.body) { + throw new Error( + `Failed to get response from AI service (status: ${response.status})${errorCodeMsg}. ` + + 'Please check network connection and endpoint configuration.' + ) + } + + // Handle other error cases throw new Error( - 'An error occurred while fetching the response (' + - response.status + - '): ' + - response.body + `AI service returned error response (status: ${response.status})${errorCodeMsg}: ` + + (typeof response.body === 'string' ? response.body : JSON.stringify(response.body)) ) }