Next.js Discord

Discord Forum

How to effectively handle errors from server actions?

Answered
Japanese cockle posted this in #help-forum
Open in Discord
Japanese cockleOP
I have a login screen that calls a server action when the user attempts to log in.

If the server action operates successfully, the server action calls redirect(...) to take me to the home screen/dashboard.

If I am unable to validate the credentials, I response with a JSON object similar to this... { status: false, message: 'Some Error' }.

It is my understanding that redirect throws a special error in order to effectively redirect the user to the new page, but my question is this....

Given that server actions are network requests that could theoretically fail, I've wrapped calls on the client in try/catch blocks, so that I can gracefully handle errors that arise. However, since redirect throws an error, my client component receive this error. Am I implementing an anti-pattern or is there a better/different way I should be tackling something like this?
Answered by B33fb0n3
This is a good guide about how to handle server action errors: https://joulev.dev/blogs/throwing-expected-errors-in-react-server-actions
View full answer

8 Replies

Answer
Japanese cockleOP
Thanks for the info. I guess my thought is… should we not be wrapping our actions in try catch in the client to handle potential networking isssues or anything else that pops up outside of “my errors”?
This is def a super helpful blog though!
Also, redirect(“/route”) should always be called outside the try catch block, so it works as expected.

For this you could only wrap the logic you’re expecting to throw an error inside the try catch block, leave anything that you’re not expecting to error out of it, including the redirect() call.

If something unexpected breaks then the user will be redirected to the closest error.tsx

If something expected breaks the user will receive feedback because you’re catching the error and handling it gracefully

If all goes well, the user will be redirected successfully because the redirect is not inside the try catch block
@Japanese cockle solved?
Japanese cockleOP
Yep 👍 ty
happy to help