Files
sarlinkportal-webui/utils/tryCatch.ts
T
shihaam 68657c92ea
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 10s
handle payment erros better
2026-08-02 15:12:01 +05:00

60 lines
1.6 KiB
TypeScript

export async function tryCatch<T, E = Error>(promise: T | Promise<T>) {
try {
const data = await promise;
return [null, data] as const;
} catch (error) {
return [error as E, null] as const;
}
}
export async function handleApiResponse<T>(
response: Response,
fnName?: string,
) {
// The backend (or an upstream gateway) can respond with a non-JSON body —
// e.g. an HTML error page on a 5xx. Parsing that as JSON throws a cryptic
// "Unexpected token '<'" error, so read the body defensively instead.
const rawBody = await response.text();
let responseData: Record<string, unknown> = {};
try {
responseData = rawBody ? JSON.parse(rawBody) : {};
} catch {
if (!response.ok) {
console.log(
`Non-JSON API error response from ${fnName} (status ${response.status}):`,
rawBody.slice(0, 500),
);
throw new Error("Please try again or contact support.");
}
}
if (response.status === 401) {
console.log("response data", responseData);
throw new Error("UNAUTHORIZED");
}
const message = responseData.message as string | undefined;
const detail = responseData.detail as string | undefined;
if (response.status === 403) {
throw new Error(
message ||
"Forbidden; you do not have permission to access this resource.",
);
}
if (response.status === 429) {
throw new Error(
message || "Too many requests; please try again later.",
);
}
if (!response.ok) {
console.log(`API Error Response from ${fnName}:`, responseData);
throw new Error(
message || detail || "Something went wrong.",
);
}
return responseData as T;
}