I have this middleware func:
func errorMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Error("Caught error in defer/recover middleware: ", err)
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(struct {
ID string
}{
err.Error(),
})
}
}()
next.ServeHTTP(w, r)
})
}
I use it like so:
router := mux.NewRouter()
router.Use(errorMiddleware)
however I am getting a compilation error, it says:
Anybody know what that's about? I am just trying to convert err to a string, ultimately, serialize it for the client etc.
recover()
returns an interface with no methods to proxy any value sent by panic()
. In the defer block, you're trying to access the Error()
method of a pure, has-no-method interface. If you want to distinguish the built-in error type, you'd have to assert its type like:
realErr, ok := err.(error)
if ok {
// here you can use realErr.Error().
}
So that it'll give you a real value of type error
. If you check out the built-in types, you'll see that error
is to implement an Error() string
method.
Type assertions: https://tour.golang.org/methods/15