From 2edba6d2148aa372cf46c14d7af1ba829619cb07 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gr=C3=A9goire=20Lodi?= <gregoire.lodi@klarna.com>
Date: Thu, 26 Oct 2023 20:29:12 +0200
Subject: [PATCH] Adds error handling in networkRequest

Sometimes the requets fails randomly and/or the content type is not json.
The lack of error handling makes consumers unable to catch the error to see what went wrong.

This commit adds error handling for both cases when the request fails (status !== 2xx)
and when the content-type is not json.
---
 src/networkRequest.ts | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/src/networkRequest.ts b/src/networkRequest.ts
index 95fead0..3b4695c 100644
--- a/src/networkRequest.ts
+++ b/src/networkRequest.ts
@@ -6,5 +6,19 @@ export const networkRequest = async (
   url: string,
 ): Promise<Record<string, unknown>> => {
   const result = await fetch(url);
+
+  const { status, headers } = result;
+
+  if (status < 200 || status >= 300) {
+    const body = await result.text();
+    throw new Error(`HTTP request failed (${status}): ${body}`);
+  }
+
+  const contentType = headers.get('content-type');
+  if (contentType?.includes('application/json') === false) {
+    const body = await result.text();
+    throw new Error(`HTTP response is not JSON but ${contentType}: ${body}`);
+  }
+
   return result.json();
 };