#return errors from queries

4 messages · Page 1 of 1 (latest)

white gate
#

what is the best practice for returing errors from queries?

gray krakenBOT
#

Hi @white gate. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources provided, here are the best practices for returning errors from queries in Convex:

  1. Use ConvexError for application errors:
    For expected failures in your query functions, you can throw a ConvexError. This allows you to carry structured information from the backend to the client.

    Example:

    throw new ConvexError("Role is already taken");
    

    You can also include additional data in the error:

    throw new ConvexError({
      message: "My fancy error message",
      code: 123,
      severity: "high",
    });
    

    Source: Application Errors

  2. Use Error Boundaries:
    The recommended way to handle errors in queries is to use React error boundary components. These allow you to catch errors thrown in their child component tree, render fallback UI, and send information about the error to your exception handling service.

    Source: Error Handling

  3. Consider returning different values:
    Instead of throwing errors, you can return different values to indicate error states. This can be especially useful with TypeScript to enforce handling of error scenarios.

    Example:

    Id<"users"> | { error: "EMAIL_ADDRESS_IN_USE" };
    

    Source: Application Errors

  4. Use exception handling services:
    It's recommended to use an exception handling service (like Sentry) along with error boundaries to manage errors effectively.

    Source: Other Recommendations

#
  1. Avoid retrying:
    Unlike other frameworks, there's no concept of "retrying" if your query function hits an error. Because Convex functions are deterministic, retrying will always produce the same error.

    Source: Error Handling

Remember, the choice between throwing errors and returning different values depends on your specific use case and how you want to handle errors in your application.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: