Skip to content

Commit 45ef270

Browse files
author
Olavo Parno
committed
fix: improve error handling in resolver with console logging
1 parent 6d5f499 commit 45ef270

File tree

3 files changed

+55
-17
lines changed

3 files changed

+55
-17
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
| Statements | Branches | Functions | Lines |
1010
| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
11-
| ![Statements](https://img.shields.io/badge/statements-87.5%25-yellow.svg?style=flat&logo=jest) | ![Branches](https://img.shields.io/badge/branches-73.17%25-red.svg?style=flat&logo=jest) | ![Functions](https://img.shields.io/badge/functions-81.81%25-yellow.svg?style=flat&logo=jest) | ![Lines](https://img.shields.io/badge/lines-88.11%25-yellow.svg?style=flat&logo=jest) |
11+
| ![Statements](https://img.shields.io/badge/statements-86.44%25-yellow.svg?style=flat&logo=jest) | ![Branches](https://img.shields.io/badge/branches-68.62%25-red.svg?style=flat&logo=jest) | ![Functions](https://img.shields.io/badge/functions-77.14%25-red.svg?style=flat&logo=jest) | ![Lines](https://img.shields.io/badge/lines-86.91%25-yellow.svg?style=flat&logo=jest) |
1212

1313
## Table of Contents
1414

src/__tests__/index.spec.ts

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,10 @@ describe('useDownloader successes', () => {
8989
});
9090

9191
describe('useDownloader failures', () => {
92+
beforeEach(() => {
93+
console.error = jest.fn();
94+
});
95+
9296
it('should be defined', () => {
9397
const { result } = renderHook(() => useDownloader());
9498
expect(result).toBeDefined();
@@ -200,11 +204,24 @@ describe('useDownloader failures', () => {
200204
expect(result.current.error).toEqual({ errorMessage: 'Custom error!' });
201205
});
202206

203-
it('should start download with error Failed to fetch', async () => {
207+
it('should start download with response.ok false and an error from the response', async () => {
204208
const { result, waitForNextUpdate } = renderHook(() => useDownloader());
205209

206210
global.window.fetch = jest.fn(() =>
207-
Promise.reject(new Error('Failed to fetch'))
211+
Promise.resolve(
212+
new Response(
213+
JSON.stringify({
214+
error: 'File download not allowed',
215+
reason:
216+
'User must complete verification before accessing this file.',
217+
}),
218+
{
219+
status: 403,
220+
statusText: 'Forbidden',
221+
headers: { 'Content-Type': 'application/json' },
222+
}
223+
)
224+
)
208225
);
209226

210227
expect(result.current.error).toBeNull();
@@ -215,7 +232,12 @@ describe('useDownloader failures', () => {
215232

216233
await waitForNextUpdate();
217234

218-
expect(result.current.error).toBeNull();
235+
expect(console.error).toHaveBeenCalledWith('403 default Forbidden');
236+
237+
expect(result.current.error).toEqual({
238+
errorMessage:
239+
'403 - Forbidden: File download not allowed: User must complete verification before accessing this file.',
240+
});
219241
});
220242

221243
describe('Tests with msSaveBlob', () => {

src/index.ts

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ export const resolver =
2222
}: ResolverProps) =>
2323
(response: Response): Response => {
2424
if (!response.ok) {
25-
throw Error(`${response.status} ${response.type} ${response.statusText}`);
25+
console.error(`${response.status} ${response.type} ${response.statusText}`);
26+
27+
throw response;
2628
}
2729

2830
if (!response.body) {
@@ -240,23 +242,37 @@ export default function useDownloader(
240242

241243
return clearInterval(intervalId);
242244
})
243-
.catch((err) => {
245+
.catch(async (error) => {
244246
clearAllStateCallback();
245-
setError((prevValue) => {
246-
const { message } = err;
247247

248-
if (message !== 'Failed to fetch') {
249-
return {
250-
errorMessage: err.message,
251-
};
248+
249+
const errorMessage = await (async () => {
250+
if (error instanceof Response) {
251+
const contentType = error.headers.get("Content-Type") || "";
252+
const isJson = contentType.includes("application/json");
253+
254+
const errorBody = isJson
255+
? await error.json().catch(() => null)
256+
: await error.text().catch(() => null);
257+
258+
return [
259+
`${error.status} - ${error.statusText}`,
260+
errorBody?.error,
261+
errorBody?.reason || (typeof errorBody === "string" ? errorBody : null),
262+
]
263+
.filter(Boolean)
264+
.join(": ");
252265
}
253-
254-
return prevValue;
255-
});
256-
266+
267+
return error?.message || "An unknown error occurred.";
268+
})();
269+
270+
setError({ errorMessage });
271+
257272
clearTimeout(timeoutId);
258-
return clearInterval(intervalId);
273+
clearInterval(intervalId);
259274
});
275+
260276
},
261277
[
262278
isInProgress,

0 commit comments

Comments
 (0)