Next.js Discord

Discord Forum

How do I actually return errors that happen in my api route?

Unanswered
Thrianta posted this in #help-forum
Open in Discord
Avatar
ThriantaOP
Hello sorry for a simple question, but how am I supposed to handle and return the errors to my client?
export async function POST(req: Request) {
  try {
    const customer = null;

    if (!customer) throw Error("Could not get customer");
    return NextResponse.json({
      message: "hello world",
    });
  } catch (error) {
    return NextResponse.error(error);
  }
}


I want to throw an error when the customer is null, which i think it does, but on the front end i only get the generic error:
{"message":"Request failed with status code 500","name":"AxiosError","stack":"AxiosError: Request //...


On the client I have no idea what caused this error.

My question is - how am I supposed to handle such errors, so that the client would clearly know that in this particular case Error happened, because the customer is null.

Should I return json object instead of throwing error?

6 Replies