Next.js Discord

Discord Forum

Form Error Handling

Answered
astro posted this in #help-forum
Open in Discord
why does my error not get logged to the console?
form:
<form
  className="space-y-4"
  onSubmit={handleSubmit(async (data) => {
    try {
      await fetch("/api/issues", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      });

      router.push("/issues");
    } catch (error) {
      console.log(error);
    }
  })}
>


route.ts
export async function POST(request: NextRequest) {
  const body: Issue = await request.json();
  const validation = createIssueSchema.safeParse(body);

  if (!validation.success) {
    return NextResponse.json(validation.error.format(), { status: 400 });
  }

  const newIssue = await prisma.issue.create({
    data: {
      title: body.title,
      description: body.description,
    },
  });

  return NextResponse.json(newIssue, { status: 200 });
}
Answered by joulev
const res = await fetch(…)
if (!res.ok) throw new Error(await res.json());

or instead of throw that error you can do anything you want
View full answer

17 Replies

also should i siwtch to axios in this case then?
@astro can you tell how to do it?
const res = await fetch(…)
if (!res.ok) throw new Error(await res.json());

or instead of throw that error you can do anything you want
Answer
If you don’t want to manually handle !res.ok, use a light wrapper like https://github.com/sindresorhus/ky
@joulev If you don’t want to manually handle !res.ok, use a light wrapper like https://github.com/sindresorhus/ky
ok so here's what i did:
try {
  const res = await fetch("/api/issues", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });

  if (!res.ok) {
    console.log(res);
  }

  router.push("/issues");
} catch (error) {
  console.log(error);
}

and i get the foollowing res
i dont get zod's validation error back in the response from the api
@joulev fetch doesn’t throw for non-20x errors. You need to manually check if res.ok is truthy and throw the error manually.
cool? give suggestions for this code(if any)
<form
  className="space-y-4"
  onSubmit={handleSubmit(async (data) => {
    const req = await fetch("/api/issues", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });

    if (!req.ok) {
      const res = await req.json();
      
      toast({
        title: "Unable to create the issue",
        description: res.title
          ? res.title._errors[0]
          : res.description._errors[0],
      });
      
      return;
    }

    router.push("/issues");
  })}
>
@joulev Lgtm, no comments
lgtm?
Look good to me
okok
thx!
@joulev Lgtm, no comments
do yk how i can implement the same logic using ky?
it seems that default error handling cannot be changed
@astro do yk how i can implement the same logic using ky? it seems that default error handling cannot be changed
I don’t use that lib myself so idk, sorry. Please consult the documentation on how to use it