HandleError is the centralised error handling and reporting.
(w http.ResponseWriter, err error)
| 36 | |
| 37 | // HandleError is the centralised error handling and reporting. |
| 38 | func HandleError(w http.ResponseWriter, err error) (code int) { |
| 39 | if err == nil { |
| 40 | return http.StatusOK |
| 41 | } |
| 42 | msg := err.Error() |
| 43 | httpCode := http.StatusInternalServerError |
| 44 | |
| 45 | // If it is recognized as HttpError emitted from cfssl, |
| 46 | // we rewrite the status code accordingly. If it is a |
| 47 | // cfssl error, set the http status to StatusBadRequest |
| 48 | switch err := err.(type) { |
| 49 | case *errors.HTTPError: |
| 50 | httpCode = err.StatusCode |
| 51 | code = err.StatusCode |
| 52 | case *errors.Error: |
| 53 | httpCode = http.StatusBadRequest |
| 54 | code = err.ErrorCode |
| 55 | msg = err.Message |
| 56 | } |
| 57 | |
| 58 | response := NewErrorResponse(msg, code) |
| 59 | jsonMessage, err := json.Marshal(response) |
| 60 | if err != nil { |
| 61 | log.Errorf("Failed to marshal JSON: %v", err) |
| 62 | } else { |
| 63 | msg = string(jsonMessage) |
| 64 | } |
| 65 | http.Error(w, msg, httpCode) |
| 66 | return code |
| 67 | } |
| 68 | |
| 69 | // ServeHTTP encapsulates the call to underlying Handler to handle the request |
| 70 | // and return the response with proper HTTP status code |
no test coverage detected
searching dependent graphs…