@@ -113,32 +113,47 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
113113
114114 var trace []string
115115 if TraceEnabled && errors .HasTrace (rsp .Error ) {
116- trace = strings .Split (errors .Trace (rsp .Error ), "\n " )
117- for index , element := range trace {
118- if strings .HasPrefix (element , "\t " ) {
119- trace [index ] = strings .Replace (element , "\t " , " " , 1 )
120- }
121- }
116+ trace = getTraceFromError (rsp .Error )
122117 }
123118
124119 // http://choly.ca/post/go-json-marshalling/
125- jsonResponse , err := json . MarshalIndent ( & struct {
120+ type apiResponse struct {
126121 Success bool `json:"success"`
127122 Error * string `json:"error"`
128123 Data interface {} `json:"data"`
129124 Trace []string `json:"_trace,omitempty"`
130- }{
125+ }
126+ jsonResponse , err := json .MarshalIndent (& apiResponse {
131127 Success : success ,
132128 Error : errorString ,
133129 Data : rsp .Data ,
134130 Trace : trace ,
135131 }, "" , " " )
136132 if err != nil {
137133 Log (r , & rsp , errors .Prefix ("Error encoding JSON response: " , err ))
134+ jsonResponse , err = json .MarshalIndent (& apiResponse {
135+ Success : false ,
136+ Error : util .PtrToString (err .Error ()),
137+ Data : rsp .Data ,
138+ Trace : getTraceFromError (err ),
139+ }, "" , " " )
140+ if err != nil {
141+ Log (r , & rsp , errors .Prefix ("Error encoding JSON response: " , err ))
142+ }
138143 }
139144
140145 w .WriteHeader (rsp .Status )
141- w .Write (jsonResponse )
146+ _ , _ = w .Write (jsonResponse )
147+ }
148+
149+ func getTraceFromError (err error ) []string {
150+ trace := strings .Split (errors .Trace (err ), "\n " )
151+ for index , element := range trace {
152+ if strings .HasPrefix (element , "\t " ) {
153+ trace [index ] = strings .Replace (element , "\t " , " " , 1 )
154+ }
155+ }
156+ return trace
142157}
143158
144159// IgnoredFormFields are ignored by FormValues() when checking for extraneous fields
0 commit comments