MCPcopy Create free account
hub / github.com/pace/bricks / WriteError

Function WriteError

http/jsonapi/runtime/error.go:80–118  ·  view source on GitHub ↗

WriteError writes a jsonapi error message to the client

(w http.ResponseWriter, code int, err error)

Source from the content-addressed store, hash-verified

78
79// WriteError writes a jsonapi error message to the client
80func WriteError(w http.ResponseWriter, code int, err error) {
81 w.Header().Set("Content-Type", JSONAPIContentType)
82 w.WriteHeader(code)
83
84 // convert error type for marshaling
85 var errList errorObjects
86
87 switch v := err.(type) {
88 case Error:
89 errList.List = append(errList.List, &v)
90 case *Error:
91 errList.List = append(errList.List, v)
92 case Errors:
93 errList.List = v
94 default:
95 errList.List = []*Error{
96 {Title: err.Error()},
97 }
98 }
99
100 reqID := w.Header().Get("Request-Id")
101
102 // update the http status code of the error
103 errList.List.setHTTPStatus(code)
104
105 // log all errors send to clients
106 log.Logger().Debug().Str("req_id", reqID).
107 Err(errList.List).Msg("error sent to client")
108 errList.List.setID(reqID)
109
110 // render the error to the client
111 enc := json.NewEncoder(w)
112 enc.SetIndent("", " ")
113 err = enc.Encode(errList)
114 if err != nil {
115 log.Logger().Info().Str("req_id", reqID).
116 Err(err).Msg("Unable to send error response to the client")
117 }
118}
119
120// Error objects MUST be returned as an array keyed by errors in the top level of a JSON API document.
121type errorObjects struct {

Callers 15

HandleErrorFunction · 0.92
TestCustomRoutesFunction · 0.92
WriteMethod · 0.92
ConflictMethod · 0.92
NotFoundMethod · 0.92
BadRequestMethod · 0.92
NotFoundMethod · 0.92
BadRequestMethod · 0.92
NotFoundMethod · 0.92
RequestTimeoutMethod · 0.92
NotFoundMethod · 0.92
BadRequestMethod · 0.92

Calls 9

LoggerFunction · 0.92
SetMethod · 0.80
HeaderMethod · 0.80
ErrMethod · 0.80
setIDMethod · 0.80
GetMethod · 0.65
WriteHeaderMethod · 0.45
ErrorMethod · 0.45
setHTTPStatusMethod · 0.45

Tested by 15

TestCustomRoutesFunction · 0.74
ConflictMethod · 0.74
NotFoundMethod · 0.74
BadRequestMethod · 0.74
NotFoundMethod · 0.74
BadRequestMethod · 0.74
NotFoundMethod · 0.74
RequestTimeoutMethod · 0.74
NotFoundMethod · 0.74
BadRequestMethod · 0.74
NotFoundMethod · 0.74
BadRequestMethod · 0.74

Used in the wild real call sites across dependent graphs

searching dependent graphs…