Files
sarlink-portal/utils/tryCatch.ts
i701 9b2f2c1528
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 11m8s
add admin checks for admin pages and run biome formating 🔨
2025-07-25 13:31:12 +05:00

42 lines
963 B
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,
) {
const responseData = await response.json();
if (response.status === 401) {
console.log("response data", responseData);
throw new Error("UNAUTHORIZED");
}
if (response.status === 403) {
throw new Error(
responseData.message ||
"Forbidden; you do not have permission to access this resource.",
);
}
if (response.status === 429) {
throw new Error(
responseData.message || "Too many requests; please try again later.",
);
}
if (!response.ok) {
console.log(`API Error Response from ${fnName}:`, responseData);
throw new Error(
responseData.message || responseData.detail || "Something went wrong.",
);
}
return responseData as T;
}