I’m using next14 and calling API for the data fetching. How to handle different API status in the app. I want to display 404, 403 and 500 pages based on the response. Also would like to display other 422 error messages. In production build I’m getting generic error message which I dont want to display.
My custom APIhandler is as follows.
try {
const res = await fetch(APIURL, APIHeaders);
if (res.status == 401) {
throw new Error("You are not authenticate.");
}
// Check if the response is in JSON format.
const contentType = res.headers.get("Content-Type");
if (!contentType || !contentType.includes("application/json")) {
throw new Error("Invalid response format");
}
const data = await res.json();
// Check if the response is ok
if (!res.ok) {
if (res.status === 404) {
return;
} else if (res.status === 403) {
throw new Error(
data.message ? data.message : "You are not allowed to access the page."
);
} else if (method === "POST") {
if (isErrorResponse(data)) {
return data;
} else if (isErrorMessage(data)) {
data.message = data.message ? data.message : errorMessage;
return data;
}
} else {
throw new Error(errorMessage);
}
}
if (revalidateTags) {
revalidateTag(`${revalidateTags}`);
}
return data;
} catch (error: any) {
console.log("x1b[41mURL:" + APIURL + "nError:" + error.message + "x1b[0m");
throw error;
}
My Error message
export default function Error({
error,
}: {
error: Error & { digest?: string };
}) {
const pathname = usePathname();
console.log("Digest Number :", error.digest);
return <p className="text-center mb-10">{error.message}</p>;
}
Can anyone share how to correct the error message and api handler file?