When I write web applications, I typically panic whenever there's an
error. Then a top-level handler "recovers" from the panic and shows an
appropriate web page with an error message to the user.
For instance, if your web application has user authentication, then
one of your handlers might have this:
user := getAuthenticatedUser()
and `getAuthenticatedUser` might look like:
type authError string
func (ae authError) Error() string {
return string(ae)
}
func getAuthenticatedUser() {
if iCannotAuthenticateYou {
panic(authError("Invalid session."))
}
}
And somewhere you have a handler through which all other handlers run:
func handler() {
defer func() {
if r := recover(); r != nil {
switch e := r.(type) {
case authError:
// Show the login screen, maybe with an error
message
default:
panic(r)
}
}
}
runOtherHandler()
}
Disclaimer: the above code is meant as a general outline. I didn't
test it and the types of the functions are probably wrong.
- Andrew