Skip to content

Instantly share code, notes, and snippets.

@zmitry
Created May 22, 2021 12:17
Show Gist options
  • Select an option

  • Save zmitry/ff26f1ad7bcfbee03239d904ec6eafff to your computer and use it in GitHub Desktop.

Select an option

Save zmitry/ff26f1ad7bcfbee03239d904ec6eafff to your computer and use it in GitHub Desktop.
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