Skip to content

Commit 5381ab8

Browse files
committed
fix: check data is present before reading errors
1 parent 6a13d1d commit 5381ab8

File tree

2 files changed

+29
-13
lines changed

2 files changed

+29
-13
lines changed

lib/request-wrapper.ts

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -648,18 +648,20 @@ function hasStringProperty(obj: any, property: string): boolean {
648648
function parseServiceErrorMessage(response: any): string | undefined {
649649
let message;
650650

651-
if (
652-
Array.isArray(response.errors) &&
653-
response.errors.length > 0 &&
654-
hasStringProperty(response.errors[0], 'message')
655-
) {
656-
message = response.errors[0].message;
657-
} else if (hasStringProperty(response, 'error')) {
658-
message = response.error;
659-
} else if (hasStringProperty(response, 'message')) {
660-
message = response.message;
661-
} else if (hasStringProperty(response, 'errorMessage')) {
662-
message = response.errorMessage;
651+
if (response) {
652+
if (
653+
Array.isArray(response.errors) &&
654+
response.errors.length > 0 &&
655+
hasStringProperty(response.errors[0], 'message')
656+
) {
657+
message = response.errors[0].message;
658+
} else if (hasStringProperty(response, 'error')) {
659+
message = response.error;
660+
} else if (hasStringProperty(response, 'message')) {
661+
message = response.message;
662+
} else if (hasStringProperty(response, 'errorMessage')) {
663+
message = response.errorMessage;
664+
}
663665
}
664666

665667
logger.info(`Parsing service error message: ${message}`);

test/unit/request-wrapper.test.js

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* (C) Copyright IBM Corp. 2019, 2021.
2+
* (C) Copyright IBM Corp. 2019, 2025.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -1015,6 +1015,20 @@ describe('formatError', () => {
10151015
'Malformed JSON string: { "errorMessage": "some error"'
10161016
);
10171017
});
1018+
1019+
it('should not throw TypeError reading properties for a response with no data', () => {
1020+
expect(() =>
1021+
requestWrapperInstance.formatError({
1022+
request: 'fake-http-request-object',
1023+
response: {
1024+
statusText: 'OK',
1025+
status: 200,
1026+
},
1027+
message: 'timed out',
1028+
code: 'ETIMEDOUT',
1029+
})
1030+
).not.toThrow();
1031+
});
10181032
});
10191033

10201034
describe('getHttpClient', () => {

0 commit comments

Comments
 (0)