From ef32e947697fc10120193cfe34426e93ff868942 Mon Sep 17 00:00:00 2001 From: martylukyy <35452459+martylukyy@users.noreply.github.com> Date: Sat, 1 Jun 2024 20:17:04 +0200 Subject: [PATCH] enhancement(web): return more meaningful error message in toast (#1558) --- web/src/api/APIClient.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/web/src/api/APIClient.ts b/web/src/api/APIClient.ts index 3bb5f1a..28a1df3 100644 --- a/web/src/api/APIClient.ts +++ b/web/src/api/APIClient.ts @@ -151,6 +151,7 @@ export async function HttpClient( } const response = await window.fetch(`${baseUrl()}${endpoint}`, init); + const isJson = response.headers.get("Content-Type")?.includes("application/json"); if (response.status >= 200 && response.status < 300) { // We received a successful response @@ -162,7 +163,6 @@ export async function HttpClient( // If Content-Type is application/json, then parse response as JSON // otherwise, just resolve the Response object returned by window.fetch // and the consumer can call await response.text() if needed. - const isJson = response.headers.get("Content-Type")?.includes("application/json"); if (isJson) { return Promise.resolve(await response.json() as T); } else { @@ -195,11 +195,23 @@ export async function HttpClient( break; } + let reason = response.statusText; + if (isJson) { + const json = await response.json(); + if (Object.hasOwn(json, "message")) { + reason = json.message as string; + } + } + + if (reason.length) { + reason = ` (${reason})`; + } + const defaultError = new Error( - `HTTP request to '${endpoint}' failed with code ${response.status} (${response.statusText})` + `HTTP request to '${endpoint}' failed with code ${response.status}${reason}` ); return Promise.reject(defaultError); - } + } } const appClient = {