Custom error page for 500 server-side errors

163 Views Asked by At

I'd like to have a custom error page for when internal server errors occur. Currently, I have my errors wrapped with panic, but this only displays "Internal server error" rather than a nice HTML page with further instructions for the user.

Is there a clean way to provide this functionality, e.g. something that monkeypatches panic in this context, as opposed to replacing every instance of panic with a call to some custom page render function?

Here's a minimal example:

// server.go
package main

import (
    "errors"
    "net/http"
    "github.com/go-martini/martini"
    "github.com/martini-contrib/render"
)

func main() {
    m := martini.Classic()
    m.Use(render.Renderer())
    m.Get("/", func(r render.Render) {
        r.HTML(http.StatusOK, "home", "World")
    })
    m.Get("/somethingbad", func(r render.Render) {
        err := errors.New("My bad error")
        if err != nil {
            panic(err)
            // can do this, but wondering if there's a better way:
            // r.HTML(http.StatusInternalServerError, "500", err.Error())
        }
    })
    m.Run()
}
<!-- templates/home.tmpl -->
<html>
    <body>
        Hello, {{.}}!
        <br />
        <a href="/somethingbad">Go here</a>
    </body>
</html>
<!-- templates/500.tmpl -->
<html>
    <body>
        500 error: {{.}}
    </body>
</html>
0

There are 0 best solutions below