rcrowley / go-tigertonic

A Go framework for building JSON web services inspired by Dropwizard

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

no obvious way to log json unmarshal errors

oryband opened this issue · comments

Let's say I have this code:

// Set main handler & context.
collectHandler :=
    tigertonic.Timed(
        corsBuilder.Build(
            tigertonic.WithContext(
                // Create context for handler.
                tigertonic.If(createContext, tigertonic.Marshaled(collect)),
                RequestContext{})),
        "Collect", nil)

If there's some JSON unmarshal problem in collect (which is a function with the correct signature), there's no obvious way to log it, besides wrapping everything with tigertonic.Logged(), which logs to much.

Is there a way to do that which I haven't figured out?

I sympathize, @oryband, so let's try to find a solution. The most obvious thing to do is just to log these errors thus:

diff --git a/marshaler.go b/marshaler.go
index db1cf4e..0940ab9 100644
--- a/marshaler.go
+++ b/marshaler.go
@@ -127,10 +127,9 @@ func (m *Marshaler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        decoder := reflect.ValueOf(json.NewDecoder(r.Body))
        out := decoder.MethodByName("Decode").Call([]reflect.Value{rq})
        if !out[0].IsNil() {
-           writeJSONError(w, NewHTTPEquivError(
-               out[0].Interface().(error),
-               http.StatusBadRequest,
-           ))
+           err := out[0].Interface().(error)
+           writeJSONError(w, NewHTTPEquivError(err, http.StatusBadRequest))
+           log.Println(err)
            return
        }
        r.Body.Close()

However, I'm sure that'll annoy someone. This is starting to feel like a job for leveled logging, which I'm always hesitant to add.

So let's take a step back and answer these questions: Why do you want to log this information? Are you expecting lots of malformed requests that you aren't sending yourself and so don't see the responses?

@rcrowley Thanks for the answer. Pretty much yes: I want to output all errorneus JSON requests to some unique error log. I also think that given the developer control & choice whether to log errors is a good idea, regardless of my specific case.