Hire me - I know how to make animation.
First, we need a function to return the error message:
export const getErrorMessage = (error: unknown): string => { let message: string; if (error instanceof Error) { message = error.message; } else if (error && typeof error === "object" && "message" in error) { message = String(error.message); } else if (typeof error === "string") { message = error; } else { message = "Something went wrong"; } return message; };
export interface ApiResponse<T> { data: T; message: string; status: number; }
Let's fetch something:
"use server"; export const fetchCurrentUser = async (): Promise<ApiResponse<any>> => { try { const res = await fetch("..."); const data = await res.json(); if (!res.ok) { return { data: {}, message: data.message || "Something went wrong", status: res.status, }; } return { data, message: "SUCCESS", status: res.status, }; } catch (error) { return { data: {}, message: getErrorMessage(error), status: 500, }; } };