SolidJSS
SolidJS12mo ago
9 replies
snnsnn

Best Practices for Handling Errors in a query-Wrapped Server Function

Hey everyone! I’ve been working with SolidStart and have a question about error handling and display strategies for server functions wrapped in a query. The example below is inspired by one of the official SolidStart examples:

export const getUser = query(async () => {
  "use server";
  try {
    const session = await getSession();
    const userId = session.data.userId;
    if (userId === undefined) throw new Error("User not found");
    const user = await db.user.findUnique({ where: { id: userId } });
    if (!user) throw new Error("User not found");
    return { id: user.id, username: user.username };
  } catch {
    await logoutSession();
    throw redirect("/login");
  }
}, "user");

In this example, if the user isn’t found, the current approach redirects to the login page. However, for a different scenario, I’d like to display an error message in the UI instead of redirecting.

I’m considering a couple of approaches:

1. Relying on Error Boundaries to catch and render the error.
2. Returning a value (e.g., { data: ..., error: ... }) that includes potential errors so I can display the appropriate state in the receiving component.

What do you think is the best way to handle this in SolidStart? I’d love to hear your thoughts and how you approach similar cases in your projects.

Thanks in advance.
Was this page helpful?