From d2acee49189658ad6a58ac78a117dac2de2bc729 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Gawe=C5=82?= Date: Wed, 24 Jul 2024 14:57:15 +0200 Subject: [PATCH] Handle parsing json errors --- src/utils.ts | 41 +++++++++++++++++------------------------ 1 file changed, 17 insertions(+), 24 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index 58914f8..116100b 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -30,14 +30,7 @@ export async function postData({ }); if (!response.ok) { - const errorBody = await response.json(); - const error = { - status: response.status, - message: errorBody.message || 'API request failed', - }; - - - throw error; + throw (await makeError(response)); } const result = await response.json(); @@ -63,14 +56,7 @@ export async function patchData({ }); if (!response.ok) { - - const errorBody = await response.json(); - const error = { - status: response.status, - message: errorBody.message || 'API request failed', - }; - - throw error; + throw (await makeError(response)); } const result = await response.json(); @@ -93,16 +79,23 @@ export async function getData({ }); if (!response.ok) { - - const errorBody = await response.json(); - const error = { - status: response.status, - message: errorBody.message || 'API request failed', - }; - - throw error; + throw (await makeError(response)); } const result = await response.json(); return result; +} + +async function makeError(response: Response) { + let errorBody: any; + try { + errorBody = await response.json(); + } catch (_) { + errorBody = null; + } + + return { + status: response.status, + message: errorBody?.message || "API request failed", + }; } \ No newline at end of file