Add REST API error message to NetworkError (#30720)

Closes #30829

Signed-off-by: moises <moises@signot.com>
This commit is contained in:
Moises Rodriguez 2024-06-26 15:49:01 -06:00 committed by GitHub
parent 2915a03c6b
commit d924db0b0b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,3 +1,5 @@
const ERROR_FIELDS = ["error", "errorMessage"];
export type NetworkErrorOptions = { response: Response; responseData: unknown };
export class NetworkError extends Error {
@ -19,7 +21,8 @@ export async function fetchWithError(
if (!response.ok) {
const responseData = await parseResponse(response);
throw new NetworkError("Network response was not OK.", {
const message = getErrorMessage(responseData);
throw new NetworkError(message, {
response,
responseData,
});
@ -42,3 +45,19 @@ export async function parseResponse(response: Response): Promise<any> {
return data;
}
function getErrorMessage(data: unknown): string {
if (typeof data !== "object" || data === null) {
return "Unable to determine error message.";
}
for (const key of ERROR_FIELDS) {
const value = (data as Record<string, unknown>)[key];
if (typeof value === "string") {
return value;
}
}
return "Network response was not OK.";
}