Created
May 22, 2021 12:17
-
-
Save zmitry/ff26f1ad7bcfbee03239d904ec6eafff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type errorHandler func(http.ResponseWriter, *http.Request) error | |
| // rootHandler implements http.Handler interface. | |
| func (fn errorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
| err := fn(w, r) // Call handler function | |
| if err == nil { | |
| return | |
| } | |
| // This is where our error handling logic starts. | |
| log.Printf("An error accured: %v", err) // Log the error. | |
| clientError, ok := err.(ClientError) // Check if it is a ClientError. | |
| if !ok { | |
| // If the error is not ClientError, assume that it is ServerError. | |
| w.WriteHeader(500) // return 500 Internal Server Error. | |
| return | |
| } | |
| body, err := clientError.ResponseBody() // Try to get response body of ClientError. | |
| if err != nil { | |
| log.Printf("An error accured: %v", err) | |
| w.WriteHeader(500) | |
| return | |
| } | |
| status, headers := clientError.ResponseHeaders() // Get http status code and headers. | |
| for k, v := range headers { | |
| w.Header().Set(k, v) | |
| } | |
| w.WriteHeader(status) | |
| w.Write(body) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment