#Error messages from convex mutations
4 messages · Page 1 of 1 (latest)
Hi @upbeat swift. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Use ConvexError instead of Error, and then catch it on the client and read its data field. Convex will only send that data to the client, not the internal stack trace. [Application errors]
1. Throw a ConvexError in your mutation
// convex/myFunctions.ts
import { mutation } from "./_generated/server";
import { ConvexError } from "convex/values";
export const myMutation = mutation({
args: {},
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) {
throw new ConvexError("You are not authorized");
}
// ...
},
});
ConvexError is designed for application errors and can carry structured data in error.data. [ConvexError class; Application errors]
2. Catch it on the client and show a toast
import { ConvexError } from "convex/values";
import { useMutation } from "convex/react";
import { api } from "@/convex/_generated/api";
function MyComponent() {
const myMutation = useMutation(api.myFunctions.myMutation);
const onClick = async () => {
try {
await myMutation({});
// success toast if you want
} catch (error) {
const message =
error instanceof ConvexError
? (error.data as string) // "You are not authorized"
: "Unexpected error occurred";
showToast(message); // your toast helper
}
};
// ...
}