r/sveltejs • u/DeadSHot_sl • 40m ago
Is there universally better way to handle errors
I am currently handle errors using various wrappers. first i wrap the endpoint or remote function with handler so i can get correct status codes and throw inside the endpoint. then i fetch the request using another function which triggers toast or global loading. if i dont did this i want to manually handle the errors loading for every request i made but i think this is hacky solution is there any better way to do it
```ts
export const POST:RequestHandler = ApiHandler(async ({ locals }) => {
if(!locals?.user) throw new UnauthorizedError()
json({})
});
```
```ts
/// ApiHandler.ts
import { json } from '@sveltejs/kit';
import type { RequestHandler } from '@sveltejs/kit';
import { mapError } from '../helpers/error-mapper';
/**
* Higher-order function that wraps a SvelteKit request handler to standardize error responses and unknowns
*/
export function ApiHandler(handler: RequestHandler): RequestHandler {
return async (event) => {
try {
return await handler(event);
} catch (e) {
const { status, body } = mapError(e);
return json(body, { status });
}
};
}
```
```ts
/// Fetch Function
export async function API<T = ApiResponse<unknown>>(
url: string,
method: "GET" | "POST" | "PATCH" | "DELETE" = "GET",
body?: object,
isRefreshRequired: boolean = false,
isToast: boolean = true
): Promise<T> {
loading.value = true;
const res = await fetch("/api" + url, {
method,
headers: body ? { "Content-Type": "application/json" } : undefined,
body: body ? JSON.stringify(body) : undefined
});
if (res.status == 404){
throw error(404,"Page not found")
}
const data = await res.json();
loading.value = false;
if (res.ok) {
if (isToast) {
showToast({
message: data.message || "Operation Successfully Completed",
status: res.status,
code: data.code
});
}
if (isRefreshRequired) {
invalidateAll()
}
} else {
toast.error(data.message);
throw error(res.status, data.message);
}
return data as T;
}
```