-
Notifications
You must be signed in to change notification settings - Fork 14
/
http_error_response_writer.go
86 lines (69 loc) · 1.85 KB
/
http_error_response_writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package common
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/anz-bank/sysl-go/log"
)
type HTTPError struct {
HTTPCode int `json:"-"`
Code string `json:"code,omitempty"`
Description string `json:"description,omitempty"`
extraFields map[string]interface{}
}
func (httpError *HTTPError) AddField(key string, val interface{}) {
if httpError.extraFields == nil {
httpError.extraFields = map[string]interface{}{}
}
httpError.extraFields[key] = val
}
func (httpError *HTTPError) GetField(key string) interface{} {
if httpError.extraFields == nil {
return nil
}
return httpError.extraFields[key]
}
type KV struct {
K string
V interface{}
}
type wrappedError struct {
e error
fields []KV
}
func (w wrappedError) Error() string {
return fmt.Sprintf("%s --- %+v", w.e.Error(), w.fields)
}
func WrappedError(err error, fields ...KV) error {
return wrappedError{
e: err,
fields: fields,
}
}
type httpErrorResponse struct {
Status interface{} `json:"status"`
}
func (httpError *HTTPError) WriteError(ctx context.Context, w http.ResponseWriter) {
var marshalTarget interface{}
marshalTarget = httpError
if len(httpError.extraFields) > 0 {
if httpError.Code != "" {
httpError.extraFields["code"] = httpError.Code
}
if httpError.Description != "" {
httpError.extraFields["description"] = httpError.Description
}
marshalTarget = httpError.extraFields
}
b, err := json.Marshal(httpErrorResponse{marshalTarget})
if err != nil {
log.Error(ctx, err, "error marshalling error response")
b = []byte(`{"status":{"code": "1234", "description": "Unknown Error"}}`)
httpError.HTTPCode = http.StatusInternalServerError
}
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
w.WriteHeader(httpError.HTTPCode)
// Ignore write error, if any, as it is probably a client issue.
_, _ = w.Write(b)
}