WriteError writes an error to the response as a JSON object. If the error is an instance of Error, the status code will be set to the error's code. Otherwise, it will return a 400 status code.
(w http.ResponseWriter, err error)
| 52 | // If the error is an instance of Error, the status code will be set to the error's code. |
| 53 | // Otherwise, it will return a 400 status code. |
| 54 | func WriteError(w http.ResponseWriter, err error) { |
| 55 | // Set content type to JSON |
| 56 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| 57 | w.Header().Set("X-Content-Type-Options", "nosniff") |
| 58 | |
| 59 | // Write the error code |
| 60 | code := http.StatusBadRequest |
| 61 | var httperr HTTPError |
| 62 | if errors.As(err, &httperr) { |
| 63 | code = httperr.StatusCode |
| 64 | } |
| 65 | w.WriteHeader(code) |
| 66 | |
| 67 | // Write error as JSON |
| 68 | obj := map[string]string{"error": err.Error()} |
| 69 | data, err := json.Marshal(obj) |
| 70 | if err != nil { |
| 71 | panic(err) |
| 72 | } |
| 73 | _, _ = w.Write(data) |
| 74 | } |
no test coverage detected