go-tigertonic icon indicating copy to clipboard operation
go-tigertonic copied to clipboard

no obvious way to log json unmarshal errors

Open oryband opened this issue 11 years ago • 2 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?

oryband avatar Oct 22 '14 11:10 oryband

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 avatar Nov 08 '14 13:11 rcrowley

@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.

oryband avatar Nov 10 '14 08:11 oryband