Skip to content

Commit 37fe8eb

Browse files
committed
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.
1 parent 8d1f028 commit 37fe8eb

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/main.ts

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -82,14 +82,27 @@ export async function run(): Promise<void> {
8282
})
8383

8484
if (isUnexpected(response)) {
85-
if (response.body.error) {
85+
// Extract x-ms-error-code from headers if available
86+
const errorCode = response.headers['x-ms-error-code']
87+
const errorCodeMsg = errorCode ? ` (error code: ${errorCode})` : ''
88+
89+
// Check if response body exists and contains error details
90+
if (response.body && response.body.error) {
8691
throw response.body.error
8792
}
93+
94+
// Handle case where response body is missing
95+
if (!response.body) {
96+
throw new Error(
97+
`Failed to get response from AI service (status: ${response.status})${errorCodeMsg}. ` +
98+
'Please check network connection and endpoint configuration.'
99+
)
100+
}
101+
102+
// Handle other error cases
88103
throw new Error(
89-
'An error occurred while fetching the response (' +
90-
response.status +
91-
'): ' +
92-
response.body
104+
`AI service returned error response (status: ${response.status})${errorCodeMsg}: ` +
105+
(typeof response.body === 'string' ? response.body : JSON.stringify(response.body))
93106
)
94107
}
95108

0 commit comments

Comments
 (0)