👌 (review) update connector error handling

Improve error handling by creating a function handler for connections on servers that use KY, and use the status key in
the response as the key to success instead of catch. Use catch if an error occurs between the client and server, not
between the server and backend.
This commit is contained in:
2025-09-13 12:50:43 +07:00
parent 3e6eae5151
commit 6d5fee823e
8 changed files with 71 additions and 9 deletions

View File

@ -1,21 +0,0 @@
export const API_BASE_URL =
process.env.MAIN_BACKEND_API_URL ?? "http://localhost";
const apiFetch = async <T = unknown>(
path: string,
init?: RequestInit
): Promise<T> => {
const res = await fetch(`${API_BASE_URL}${path}`, {
...init,
headers: {
"Content-Type": "application/json",
...init?.headers,
},
cache: "no-store",
});
if (!res.ok) throw new Error(await res.text());
return res.json();
};
export default apiFetch;

View File

@ -1,11 +0,0 @@
import { useRouter } from "next/navigation";
export const delayButtonClick = (
router: ReturnType<typeof useRouter>,
href: string,
timeout: number = 300
) => {
setTimeout(() => {
router.push(href);
}, timeout);
};

View File

@ -0,0 +1,12 @@
"use server";
import ky from "ky";
export const api = ky.create({
prefixUrl: process.env.MAIN_BACKEND_API_URL,
credentials: "include",
headers: {
access_token: process.env.MAIN_BACKEND_API_KEY,
},
retry: 0,
});

View File

@ -0,0 +1,26 @@
"use server";
import { HTTPError } from "ky";
export const apiErrorHandler = async (
error: unknown,
safeFail: boolean = false
) => {
if (error instanceof HTTPError) {
return {
success: false,
status: error.response.status,
text: await error.response.json(),
};
}
if (safeFail) {
return {
success: false,
status: 500,
text: { message: "An unexpected error occurred" },
};
} else {
throw error;
}
};