diff --git a/js/libs/keycloak-admin-client/src/utils/fetchWithError.ts b/js/libs/keycloak-admin-client/src/utils/fetchWithError.ts index d255664d78..57171dc50e 100644 --- a/js/libs/keycloak-admin-client/src/utils/fetchWithError.ts +++ b/js/libs/keycloak-admin-client/src/utils/fetchWithError.ts @@ -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 { 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)[key]; + + if (typeof value === "string") { + return value; + } + } + + return "Network response was not OK."; +}