Next.js Discord

Discord Forum

How to show errors on client using server actions ?

Unanswered
Tan posted this in #help-forum
Open in Discord
TanOP
Hi I was writing actions for backend. And when some error occurs I am throwing them and catching from forontend and display that error using toast. On development it works but while in production I mean after building the app Next's Error handler intercept and show different error message.

It is a form and I was checking if the form is empty. My server action looks like this:
export const someFunc = async (data) => {
  const user = await getCurrentUser();
  if (!user) throw new Error("Unauthorized");

  const parsedData = parseFormData(data);

  if (!parsedData.valid) throw new Error("Bad request");

  if (!(await checkRateLimit(user.id))) throw new Error("Rate limit exceeded");

  if (Object.keys(parsedData.data).length === 0)
    throw new Error("Empty form submission");

  // Continue with the rest of the function logic...
};


And I am showing the error or success message like this in frontend.
const handleSubmit = async (formData: TForm) => {
  try {
    await linkSocialMedia(formData);
    redirectToDashboard();
  } catch (error) {
    console.error(error);
    displayErrorMessage(error?.message || "An error occurred");
    setLoading(false);
  }
};

3 Replies

You could possible make your server action return an object, for example:
export const someFunc = async (data) => {
    const user = await getCurrentUser();
    if (!user) {
        return { error: "Unauthorized" };
    }
  
    const parsedData = parseFormData(data);
  
    if (!parsedData.valid) {
        return { error: "Invalid form data" };
    }
  
    if (!(await checkRateLimit(user.id))) {
        return { error: "Rate limit exceeded" };
    }
  
    if (Object.keys(parsedData.data).length === 0)
      throw new Error("Empty form submission");
  
    // Continue with the rest of the function logic...
  };


On your frontend you would need to handle the server action like this:
const handleSubmit = async (formData: TForm) => {
    const result = await someFunc();
    if (result.error) {
        //handle your error handling here (result holds the returned object from your server action, for example it could hold: 'error: "Rate limit exceeded"'
        return; // add return statement to make the onclick stop executing any further.
    }

    // handle the rest of the logic here
};