zid
zid12mo ago

Handling errors from convex

Hey Team, is there a better way to handle/throw convex errors to the client? I have a particular setup for one part of my app where it would be very efficient if I could simply throw the error directly from the server. Here's the way I'm handling this now
const handleUpdateSkill = async ({ type, skill }) => {
try {
await updateSkill({
userId,
type,
skill,
});
} catch (error) {
let errorMessage = error.message || "Cannot add more skills";

// First, remove the known prefix if it's there
const prefixToRemove = "[CONVEX M(arsenal:updateSkill)] Uncaught Error: ";
errorMessage = errorMessage.replace(prefixToRemove, "");

// Now, remove any trailing details after "at handler"
errorMessage = errorMessage.split("\n")[0];

toast.error(errorMessage);
}
};
const handleUpdateSkill = async ({ type, skill }) => {
try {
await updateSkill({
userId,
type,
skill,
});
} catch (error) {
let errorMessage = error.message || "Cannot add more skills";

// First, remove the known prefix if it's there
const prefixToRemove = "[CONVEX M(arsenal:updateSkill)] Uncaught Error: ";
errorMessage = errorMessage.replace(prefixToRemove, "");

// Now, remove any trailing details after "at handler"
errorMessage = errorMessage.split("\n")[0];

toast.error(errorMessage);
}
};
5 Replies
lee
lee12mo ago
Application Errors | Convex Developer Hub
If you have expected ways your functions might fail, you can either return
lee
lee12mo ago
The prefix-stripping code will work in dev deployments, but not in prod (because of this https://docs.convex.dev/functions/error-handling/#differences-in-error-reporting-between-dev-and-prod )
Error Handling | Convex Developer Hub
There are four reasons why your Convex
zid
zidOP12mo ago
Ah, I see. below seems to work. The example in the docs however shows error.data.message, where for me, message is undefined.
catch (error) {
let errorMessage = "Can't add any more.";

if (error instanceof ConvexError && error?.data) {
errorMessage = error.data;
}

toast.error(errorMessage);
}
catch (error) {
let errorMessage = "Can't add any more.";

if (error instanceof ConvexError && error?.data) {
errorMessage = error.data;
}

toast.error(errorMessage);
}
And thank you!
lee
lee12mo ago
Yeah data is just the argument to ConvexError, so the doc's example uses ConvexError({message: "fancy"}) which makes error.data.message defined. If you're passing a string to ConvexError, your code looks great to handle it
zid
zidOP12mo ago
Ah interesting; and thank you again!

Did you find this page helpful?