Next.js Discord

Discord Forum

showing errors from Server Actions

Answered
Pine Bunting posted this in #help-forum
Open in Discord
Pine BuntingOP
I love the idea of catching server errors within error boundaries from server actions. but there may be some errors that i need to let the user know. for example;

I have a server action like this:

export async function login(formData: FormData) {
  try {
    const username = formData.get("username");
    const password = formData.get("password");
    if (!username || !password) {
      throw new Error("Username or password is missing!");
    }
    if (username instanceof File || password instanceof File) {
      throw new Error("Username and password must be strings!");
    }
    const user = await signInWithEmail(username, password);
    const session = await getSession();
    session.userId = user.uid;
    await session.save();
  } catch (error) {
    return (error instanceof Error) ? { message: error.message } : { message: "unknown error" };
  }
  redirect("/dashboard");
}


signInWithEmail function might throw errors such as:

throw new Error("Incorrect username or password. Please try again.");


I try to use that server action in a form like this

<Form action={login}>
...
</Form>


and I just wonder how can i show this error to the user? what is the best approach to handling errors without breaking the error boundaries design?

9 Replies

Answer
@Ray https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#server-side-validation-and-error-handling
Pine BuntingOP
I tried this before. but couldn't figure out how to redirect without breaking PE
Pine BuntingOP
yea
since redirect throw NEXT_REDIRECT error, if you are using it inside try/catch block, you will need to rethrow it
@Pine Bunting yea
like this
export async function login(formData: FormData) {
  try {
    const username = formData.get("username");
    const password = formData.get("password");
    if (!username || !password) {
      return {
        error: "Username or password is missing!",
      };
    }
    if (username instanceof File || password instanceof File) {
      return {
        error: "Username and password must be strings!",
      };
    }
    const user = await signInWithEmail(username, password);
    const session = await getSession();
    session.userId = user.uid;
    await session.save();
  } catch (error) {
    if (error instanceof Error && error.message === "NEXT_REDIRECT")
      throw error;
    return error instanceof Error
      ? { message: error.message }
      : { message: "unknown error" };
  }
}
and use it with useFormState
Pine BuntingOP
yeah that worked. thanks!