Skip to content

Commit

Permalink
Add log to read json error (#214)
Browse files Browse the repository at this point in the history
  • Loading branch information
KeinAsylum authored Jul 17, 2023
1 parent d2e6368 commit ae2b3f0
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 8 deletions.
12 changes: 8 additions & 4 deletions src/app/backend/fetch-capi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,12 @@ describe('fetch capi', () => {
});

test('should catch json reject', async () => {
const mockFetch = jest.fn();
mockFetch.mockResolvedValue({
const errorMsg = 'Read json error';
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});

const mockFetch = jest.fn().mockResolvedValue({
status: 500,
json: async () => Promise.reject()
json: async () => Promise.reject(errorMsg)
});
global.fetch = mockFetch;

Expand All @@ -92,8 +94,10 @@ describe('fetch capi', () => {
try {
await fetchCapi({ endpoint, accessToken });
} catch (error) {
expect(error).toStrictEqual({ responseStatus: 500 });
expect(error).toEqual(errorMsg);
}
expect(errorSpy).toHaveBeenCalled();
errorSpy.mockRestore();
});

test('should retry failed fetch requests', async () => {
Expand Down
7 changes: 4 additions & 3 deletions src/app/backend/fetch-capi.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { guid } from 'checkout/utils';
import guid from 'checkout/utils/guid';
import delay from 'checkout/utils/delay';

export type FetchCapiParams = {
Expand All @@ -13,7 +13,8 @@ const provideResponse = async (response: Response) => {
const json = await response.json();
return response.status >= 200 && response.status <= 300 ? json : Promise.reject(json);
} catch (ex) {
return Promise.reject({ responseStatus: response.status });
console.error('Read response json error', ex);
return Promise.reject(ex);
}
};

Expand All @@ -39,7 +40,7 @@ const doFetch = async (param: FetchCapiParams, retryDelay: number, retryLimit: n
}
};

export const fetchCapi = async <T>(param: FetchCapiParams, retryDelay = 500, retryLimit = 20): Promise<T> => {
export const fetchCapi = async <T>(param: FetchCapiParams, retryDelay = 1000, retryLimit = 20): Promise<T> => {
const response = await doFetch(param, retryDelay, retryLimit);
return provideResponse(response);
};
4 changes: 3 additions & 1 deletion src/app/utils/guid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ function s4() {
.substring(1);
}

export function guid() {
function guid() {
return `${s4()}${s4()}-${s4()}${s4()}`;
}

export default guid;

0 comments on commit ae2b3f0

Please sign in to comment.