Proper way to inform the user of error on server action

lets assume that there is a server action with multiple insert in if condition . and on one of there inserts there was a database error.
what is the correct way to set an error text and pass it to the client

You can use the “catch” step in the server action.
Normally, if you have not defined any steps under catch and some of the steps in your server action results in an error - then the server action just ends, and an error message is generated.

If you want to create your own error handler, like for example - sending an email, when there was an error during executing the server action, you place the send mail step under catch.

Another example - you insert some data into the db and then upload an image related with this record, but the upload returns an error then you can remove the last inserted record in the catch steps.

Or you can use the Add Response with a custom error status and show a notification on the page.

BTW - if it is a server error, you can directly use the on error event on the front end and show a notification saying “Something went wrong” message, as the server action will return an error 500.

3 Likes

this is my main concern. so i how do i know what part of the server action did run correctly and where did it have an error.
and roll back all the changes.
should i have a condition on every server action with catch actions? will the server action stop after the rist error?