Add REST API error message to NetworkError
(#30720)
Closes #30829 Signed-off-by: moises <moises@signot.com>
This commit is contained in:
parent
2915a03c6b
commit
d924db0b0b
1 changed files with 20 additions and 1 deletions
|
@ -1,3 +1,5 @@
|
||||||
|
const ERROR_FIELDS = ["error", "errorMessage"];
|
||||||
|
|
||||||
export type NetworkErrorOptions = { response: Response; responseData: unknown };
|
export type NetworkErrorOptions = { response: Response; responseData: unknown };
|
||||||
|
|
||||||
export class NetworkError extends Error {
|
export class NetworkError extends Error {
|
||||||
|
@ -19,7 +21,8 @@ export async function fetchWithError(
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const responseData = await parseResponse(response);
|
const responseData = await parseResponse(response);
|
||||||
throw new NetworkError("Network response was not OK.", {
|
const message = getErrorMessage(responseData);
|
||||||
|
throw new NetworkError(message, {
|
||||||
response,
|
response,
|
||||||
responseData,
|
responseData,
|
||||||
});
|
});
|
||||||
|
@ -42,3 +45,19 @@ export async function parseResponse(response: Response): Promise<any> {
|
||||||
|
|
||||||
return data;
|
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.";
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue