Dealing with database error in a web app

131 views
Skip to first unread message

Tech163

unread,
Mar 29, 2013, 10:19:15 AM3/29/13
to golang-nuts
I'm writing a web app in go that is going to be using a database. what's
the best way to detect a database error and show an error page?

I have a func(w http.ResponseWriter, r *http.Request) that queries the
database. The best idea I've come up with is checking err != nil every
single time a query is run, displaying an error page, and return so
execution does not continue for that function. Is this the most
effective way to do what I'm doing?

Thanks

Fábio Gomes

unread,
Mar 29, 2013, 10:43:02 AM3/29/13
to golan...@googlegroups.com
Nice, I have the same doubt.

So far I'm using http.Error(w, err.Error(), http.StatusInternalServerError) but I also don't know if its the best way.

Looking forward to the answers :)

decitrig

unread,
Mar 30, 2013, 8:44:40 AM3/30/13
to golan...@googlegroups.com
In my webapp, I created wrapper interfaces and funcs for serving http requests, so that inside the app the handlers are func(w http.ResponseWriter, r *http.Request) *webapp.Error. Then they just return nil or errors as need be, and the top level handler checks those errors and can server error pages or what have you. The toplevel handler, which is a vanilla http.HandlerFunc, handles "/", and then dispatches to the internal handlers (I use www.gorillatoolkit.com, btw).
 

Thanks

Andrew Gallant

unread,
Mar 30, 2013, 10:55:48 AM3/30/13
to golang-nuts
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
Reply all
Reply to author
Forward
0 new messages