WriteError writes a jsonapi error message to the client
(w http.ResponseWriter, code int, err error)
| 78 | |
| 79 | // WriteError writes a jsonapi error message to the client |
| 80 | func 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. |
| 121 | type errorObjects struct { |
searching dependent graphs…