Skip to content

Commit ae8ef22

Browse files
authored
Update json.go
fix bug WriteErrorCode function always returns 500 code inside JSON payload
1 parent 3179543 commit ae8ef22

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

json.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ func UnescapedHTML(enc *json.Encoder) {
3131
// JSONWriter writes JSON responses (obviously).
3232
type JSONWriter struct {
3333
Reporter ErrorReporter
34-
ErrorEnhancer func(r *http.Request, err error) interface{}
34+
ErrorEnhancer func(r *http.Request, code int, err error) interface{}
3535
EnableDebug bool
3636
}
3737

@@ -54,15 +54,15 @@ type ErrorEnhancer interface {
5454
EnhanceJSONError() interface{}
5555
}
5656

57-
func defaultJSONErrorEnhancer(r *http.Request, err error) interface{} {
57+
func defaultJSONErrorEnhancer(r *http.Request, code int, err error) interface{} {
5858
if e, ok := err.(ErrorEnhancer); ok {
5959
return e.EnhanceJSONError()
6060
}
61-
return &ErrorContainer{Error: ToDefaultError(err, r.Header.Get("X-Request-ID"))}
61+
return &ErrorContainer{Error: ToDefaultError(err, code, r.Header.Get("X-Request-ID"))}
6262
}
6363

64-
func Scrub5xxJSONErrorEnhancer(r *http.Request, err error) interface{} {
65-
payload := defaultJSONErrorEnhancer(r, err)
64+
func Scrub5xxJSONErrorEnhancer(r *http.Request, code int, err error) interface{} {
65+
payload := defaultJSONErrorEnhancer(r, code, err)
6666

6767
if de, ok := payload.(DefaultError); ok {
6868
if de.StatusCode() >= 500 {
@@ -78,7 +78,7 @@ func Scrub5xxJSONErrorEnhancer(r *http.Request, err error) interface{} {
7878
}
7979

8080
// We have some other error, which we always want to scrub.
81-
return &ErrorContainer{Error: ToDefaultError(&ErrInternalServerError, r.Header.Get("X-Request-ID"))}
81+
return &ErrorContainer{Error: ToDefaultError(&ErrInternalServerError, code, r.Header.Get("X-Request-ID"))}
8282
}
8383

8484
func scrub5xxError(err *DefaultError) *ErrorContainer {
@@ -164,7 +164,7 @@ func (h *JSONWriter) WriteErrorCode(w http.ResponseWriter, r *http.Request, code
164164
// Enhancing must happen after logging or context will be lost.
165165
var payload interface{} = err
166166
if h.ErrorEnhancer != nil {
167-
payload = h.ErrorEnhancer(r, err)
167+
payload = h.ErrorEnhancer(r,code, err)
168168
}
169169
if de, ok := payload.(*DefaultError); ok && !h.EnableDebug {
170170
de2 := *de

0 commit comments

Comments
 (0)