#convexerror handling

4 messages · Page 1 of 1 (latest)

brazen aspen
#

const errorMessage = error instanceof ConvexError
? (error.data as { message: string }).message
: "Unexpected error occurred";

this const value is undefined when i throw convexerror on the query, it's actually a convexerror but im not accesing the message correctly, fix it

dusk cosmosBOT
#

Hi @brazen aspen. 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 information provided in the knowledge sources, it appears that you're encountering an issue with accessing the error message from a ConvexError thrown in a query. Let's address this problem:

The issue likely stems from how you're accessing the data property of the ConvexError. According to the Convex documentation and examples provided, you can access the error message directly from the data property without casting it to a specific type. Here's how you can fix it:

const errorMessage = error instanceof ConvexError
                ? error.data
                : "Unexpected error occurred";

This approach should work because when you throw a ConvexError, you can pass the error message directly to the constructor, as shown in this example from the Convex documentation on Application Errors (https://docs.convex.dev/functions/error-handling/application-errors#throwing-application-errors):

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

In this case, error.data will directly contain the string "Role is already taken".

If you're using a more complex error structure, you might need to adjust your access accordingly. For example, if you're throwing the error like this:

throw new ConvexError({ message: "My fancy error message" });

Then you would access it like this:

const errorMessage = error instanceof ConvexError
                ? error.data.message
                : "Unexpected error occurred";

If you're still having issues, you might want to console.log the entire error object to see its structure:

console.log(error);

This will help you understand the exact shape of the error and how to access its properties correctly.

#

Remember that error handling for queries in React components is typically done using error boundaries, as mentioned in the Convex documentation on error handling (https://docs.convex.dev/functions/error-handling/#errors-in-queries). However, if you need more granular control, you might consider using the "richer useQuery" from the convex-helpers package, which provides direct access to errors in the component as suggested in this Discord thread (https://discord.com/channels/1019350475847499849/1253581087003775017).

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