0

I'm working on a Next.js 14 project, and I have a setup where I make API requests using fetch in a handler.tsx file like this:

async function getPositions() {
  const response = await fetch(
    process.env.BASE_API_URL + "/positions?enabled=true",
    {
      cache: "no-cache",
    }
  );

  if (!response.ok) {
    throw new Error("Es gab ein Problem mit Ihrer Anfrage");
  }

  const data = await response.json();
  return data.result;
}

export { getPositions };

In my page file page.tsx I simply call the getPositions function and assume that any server-side errors will be caught in a global error handler:

import { getPositions } from "./handler";

export default async function Page() {
  const positions = await getPositions();

  console.log(positions);

  return (
    <>
      <h1>Positions</h1>
    </>
  );
}

According to the Next.js documentation, it seems like I don't have to catch the error explicitly and can let it propagate through to be caught in a separate error handler error.tsx. Is this approach correct and are there any best practices for handling server-side errors in Next.js 14?

2 Answers 2

1

This is perfectly fine approach

However you can add your error.jsx closer to your page to prevent disabling full ui to your users

Sign up to request clarification or add additional context in comments.

4 Comments

Thx, is it normal that the next js still shows the error in the console and with its red toast in the bottom left?
Yes, this is normal behavior, it show to help you debugging errors, in production build, there will no such error explanations
error.js is a client component, it won't render on the server and therefore won't log the server side errors.
Okay but what if you don't want to have your whole page replaced by the error.tsx? I see that works if you just want to show an error page, but sometimes you have multiple fetches and only want to show an error message on that specific place.
0

you can also try this in Next 14 , APP router , server side

return NextResponse.json({message:Internal Server error, status:500})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.