apiserver: refactor handleError in endpoints/filters

This commit is contained in:
Abu Kashem 2024-01-09 13:32:09 -05:00
parent 445869a59b
commit 9e37ccedc7
No known key found for this signature in database
GPG Key ID: E5ECC1124B5F9C68
2 changed files with 10 additions and 7 deletions

View File

@ -58,7 +58,7 @@ func withRequestDeadline(handler http.Handler, sink audit.Sink, policy audit.Pol
requestInfo, ok := request.RequestInfoFrom(ctx)
if !ok {
handleError(w, req, http.StatusInternalServerError, fmt.Errorf("no RequestInfo found in context, handler chain must be wrong"))
handleError(w, req, http.StatusInternalServerError, nil, "no RequestInfo found in context, handler chain must be wrong")
return
}
if longRunning(req, requestInfo) {
@ -166,8 +166,12 @@ func parseTimeout(req *http.Request) (time.Duration, bool, error) {
return timeout, true, nil
}
func handleError(w http.ResponseWriter, r *http.Request, code int, err error) {
errorMsg := fmt.Sprintf("Error - %s: %#v", err.Error(), r.RequestURI)
http.Error(w, errorMsg, code)
klog.Errorf(errorMsg)
// handleError does the following:
// a) it writes the specified error code, and msg to the ResponseWriter
// object, it does not print the given innerErr into the ResponseWriter object.
// b) additionally, it prints the given msg, and innerErr to the log with other
// request scoped data that helps identify the given request.
func handleError(w http.ResponseWriter, r *http.Request, code int, innerErr error, msg string) {
http.Error(w, msg, code)
klog.ErrorSDepth(1, innerErr, msg, "method", r.Method, "URI", r.RequestURI, "auditID", audit.GetAuditIDTruncated(r.Context()))
}

View File

@ -18,7 +18,6 @@ package filters
import (
"context"
"fmt"
"net/http"
"time"
@ -39,7 +38,7 @@ func WithLatencyTrackers(handler http.Handler) http.Handler {
ctx := req.Context()
requestInfo, ok := request.RequestInfoFrom(ctx)
if !ok {
handleError(w, req, http.StatusInternalServerError, fmt.Errorf("no RequestInfo found in context, handler chain must be wrong"))
handleError(w, req, http.StatusInternalServerError, nil, "no RequestInfo found in context, handler chain must be wrong")
return
}