DefaultErrorEncoder writes the error to the ResponseWriter, by default a content type of text/plain, a body of the plain text of the error, and a status code of 500. If the error implements Headerer, the provided headers will be applied to the response. If the error implements json.Marshaler, and th
(_ context.Context, err error, w http.ResponseWriter)
| 188 | // encoded form of the error will be used. If the error implements StatusCoder, |
| 189 | // the provided StatusCode will be used instead of 500. |
| 190 | func DefaultErrorEncoder(_ context.Context, err error, w http.ResponseWriter) { |
| 191 | contentType, body := "text/plain; charset=utf-8", []byte(err.Error()) |
| 192 | if marshaler, ok := err.(json.Marshaler); ok { |
| 193 | if jsonBody, marshalErr := marshaler.MarshalJSON(); marshalErr == nil { |
| 194 | contentType, body = "application/json; charset=utf-8", jsonBody |
| 195 | } |
| 196 | } |
| 197 | w.Header().Set("Content-Type", contentType) |
| 198 | if headerer, ok := err.(Headerer); ok { |
| 199 | for k, values := range headerer.Headers() { |
| 200 | for _, v := range values { |
| 201 | w.Header().Add(k, v) |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | code := http.StatusInternalServerError |
| 206 | if sc, ok := err.(StatusCoder); ok { |
| 207 | code = sc.StatusCode() |
| 208 | } |
| 209 | w.WriteHeader(code) |
| 210 | w.Write(body) |
| 211 | } |
| 212 | |
| 213 | // StatusCoder is checked by DefaultErrorEncoder. If an error value implements |
| 214 | // StatusCoder, the StatusCode will be used when encoding the error. By default, |
nothing calls this directly
no test coverage detected
searching dependent graphs…