Nishil Faldu
Nishil Faldu9mo ago

Propagating errors in mutations in server actions

Helloooo. Recently, I have been thoroughly enjoying using convex mutations in server-actions but I did run into something for which I would like some help. So lets say, my mutations throw a ConvexError , I have an async function in my use server file (where all my actions are) where I call the convex mutation using fetchMutation call - which is wrapped in a try-catch - if there's an error I will try to re-throw the error. I call this async function in another file (a react component, lets say) where I catch the re-thrown error in a toast but it doesn't give the same error message I threw from backend using ConvexError and it gives me this instead: An error occurred in the Server Components render which I think is because the re-thrown error cannot be serialized. Does anyone know a way around this or have a better solution?
6 Replies
ballingt
ballingt9mo ago
What would you like to have happen here? This sounds right, if you rethrow the error this is also what would happen on the client.
Nishil Faldu
Nishil FalduOP9mo ago
i would love for the toast to use the same error as thrown by convex
ballingt
ballingt9mo ago
I would make your server action an object like
let result;
try {
const result = await fetchMutation();
return {
success: true,
result: "resultstring"
}
} catch (e) {
return {
success: false,
errorMessage: e.message
};
}
let result;
try {
const result = await fetchMutation();
return {
success: true,
result: "resultstring"
}
} catch (e) {
return {
success: false,
errorMessage: e.message
};
}
Does your framework serialized normal errors thrown in server actions? @Nishil Faldu I'm wondering whether you're expecting the error to be serialized because that's how other server actions work, or if you were just hoping that Convex errors would be special
Nishil Faldu
Nishil FalduOP9mo ago
i do have it setup like that for now I'd like errors to be serialized but I dont think nextjs allows that i was just hoping there's direct solution rather than returning an object from server-action and then checking for success/error and then throwing a toast...but I guess this is the only way
ballingt
ballingt9mo ago
yeah that I know of, but if Next.js does some error serialization for server actions we're definitely interested in making sure our errors work too
Nishil Faldu
Nishil FalduOP9mo ago
yeah that would be super cool honestly. but thanks for looking into this, i appreciate it

Did you find this page helpful?