Error handling best practices with Server Actions
Answered
Sun bear posted this in #help-forum
Sun bearOP
I'm using server actions directly as form actions in my project to benefit from progressive enhancement (i.e. the form works even without having JavaScript enabled). In this sort of a use case, what best practices are there for throwing and catching errors from the Server Action? For example, input validation errors.
* I was initially thinking of error boundaries, but it seems that you can't really really include any information in the errors, as those are stripped out in prod
* Another thought I had was redirecting back to the form, but with query parameters that indicate the error (e.g.
* Finally, I thought about returning data from the action, but as far as I know there's no way to consume this data without running JS on the client and calling the server action that way
Are there any best practices around this? Anyone handled a similar case in their project?
* I was initially thinking of error boundaries, but it seems that you can't really really include any information in the errors, as those are stripped out in prod
* Another thought I had was redirecting back to the form, but with query parameters that indicate the error (e.g.
?error=noEmail)* Finally, I thought about returning data from the action, but as far as I know there's no way to consume this data without running JS on the client and calling the server action that way
Are there any best practices around this? Anyone handled a similar case in their project?
Answered by Giant panda
There is no error handling for server actions yet. The React team is still working on it. If you call them outside of form actions I suggest returning Either monads in case you're familiar with them or alternatively simple responses using a discriminator like:
type ActionResponse =
| {
kind: 'success'
}
| {
kind: 'error',
description: '...'
// w/e you need
}
;12 Replies
Sun bearOP
Bump 🙂
Sun bearOP
Bumping this again
Giant panda
There is no error handling for server actions yet. The React team is still working on it. If you call them outside of form actions I suggest returning Either monads in case you're familiar with them or alternatively simple responses using a discriminator like:
type ActionResponse =
| {
kind: 'success'
}
| {
kind: 'error',
description: '...'
// w/e you need
}
;Answer
Sun bearOP
Yeah, calling them outside server actions would make it easy, but I'd like to keep the form working without JS as well
Giant panda
In case of form actions old school query params are working just as fine like we did in PHP decades ago
Sun bearOP
😄
I have fond memories of that time, maybe it's time to embrace it again
glad to hear the React team has plans in this area though
looking forward to that
Giant panda
There is nothing wrong with that approach I'd say
Sun bearOP
yeah, it works and is relatively low tech
thanks Near!