34 lines
738 B
TypeScript
34 lines
738 B
TypeScript
import { HTTPError } from "ky";
|
|
|
|
export interface ApiError {
|
|
/**
|
|
* Client error response status code
|
|
*/
|
|
status: number;
|
|
/**
|
|
* Error message
|
|
*/
|
|
message: string;
|
|
}
|
|
|
|
/**
|
|
* Helper function that calls Ky and manages its errors;
|
|
* @returns A tuple [data, error] in Golang-like fashion
|
|
*/
|
|
export async function callApi<T>(
|
|
fn: () => Promise<T>,
|
|
): Promise<[T, null] | [null, ApiError]> {
|
|
try {
|
|
const data = await fn();
|
|
return [data, null];
|
|
} catch (error) {
|
|
if (error instanceof HTTPError) {
|
|
const body = await error.response.json<{ message: string }>();
|
|
return [null, { status: error.response.status, message: body.message }];
|
|
}
|
|
|
|
// re-throw unexpected errors
|
|
throw error;
|
|
}
|
|
}
|