enhancement(web): return more meaningful error message in toast (#1558)

This commit is contained in:
martylukyy 2024-06-01 20:17:04 +02:00 committed by GitHub
parent f472859cb0
commit ef32e94769
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -151,6 +151,7 @@ export async function HttpClient<T = unknown>(
} }
const response = await window.fetch(`${baseUrl()}${endpoint}`, init); 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) { if (response.status >= 200 && response.status < 300) {
// We received a successful response // We received a successful response
@ -162,7 +163,6 @@ export async function HttpClient<T = unknown>(
// If Content-Type is application/json, then parse response as JSON // If Content-Type is application/json, then parse response as JSON
// otherwise, just resolve the Response object returned by window.fetch // otherwise, just resolve the Response object returned by window.fetch
// and the consumer can call await response.text() if needed. // and the consumer can call await response.text() if needed.
const isJson = response.headers.get("Content-Type")?.includes("application/json");
if (isJson) { if (isJson) {
return Promise.resolve<T>(await response.json() as T); return Promise.resolve<T>(await response.json() as T);
} else { } else {
@ -195,8 +195,20 @@ export async function HttpClient<T = unknown>(
break; 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( 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); return Promise.reject(defaultError);
} }