-
Summary
Additional informationAccording to the documentation, "In Server Actions and Route Handlers, redirect should be called after the try/catch block." I believe the reason is that redirect internally throws an error, so if it's called inside a try block, it will be caught by the corresponding catch, which could interfere with the redirect behavior. However, calling redirect inside a catch block shouldn't cause issues, since it would be the final action in the error-handling flow. If that's correct, then saying "redirect should be called after the try/catch block" might be misleading. The phrase "after the try/catch block" seems to imply that both try and catch must be exited before calling redirect, which isn't necessarily true—calling it inside catch should be fine. Does that sound correct? And is it also safe to call redirect inside a catch block? ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Technically, yeah, all you want is to avoid catching the thrown exception, cuz that'd "block" the redirect attempt. I think though, it does sound like a good idea to decouple the try/catch handling block from the redirect logic. For example here, if let data = null
try {
data = await getData();
} catch(reason) {
handleReasonForDataFailure(reason)
logErrors(reason)
}
if (!data) {
redirect()
} Cuz otherwise, you likely need to have duplicated redirect calls. For example, if let data = null
try {
data = await getData();
} catch(reason) {
handleReasonForDataFailure(reason)
redirect()
// also any code after this line won't run
}
// if data is still not in the right shape
if (isInvalid(data)) redirect() A I am gonna do some other fix to the docs, I'll include this there.
That does read a bit weird though, but it is the correct thing to say. |
Beta Was this translation helpful? Give feedback.
Technically, yeah, all you want is to avoid catching the thrown exception, cuz that'd "block" the redirect attempt.
I think though, it does sound like a good idea to decouple the try/catch handling block from the redirect logic.
For example here, if
getData
throws - then you handle the errors, log and what not, and then separately decide what to do in terms of the UI.Cuz otherwise, you likely need to have duplicated redirect calls. For example, if
getData
is fetch based, it might itself not throw on 404's etc..