Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame] | 1 | /* |
| 2 | Copyright 2016 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package filters |
| 18 | |
| 19 | import ( |
| 20 | "net/http" |
| 21 | "runtime/debug" |
| 22 | |
| 23 | "github.com/golang/glog" |
| 24 | |
| 25 | "k8s.io/apimachinery/pkg/util/runtime" |
| 26 | "k8s.io/apiserver/pkg/server/httplog" |
| 27 | ) |
| 28 | |
| 29 | // WithPanicRecovery wraps an http Handler to recover and log panics. |
| 30 | func WithPanicRecovery(handler http.Handler) http.Handler { |
| 31 | return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 32 | defer runtime.HandleCrash(func(err interface{}) { |
| 33 | http.Error(w, "This request caused apiserver to panic. Look in the logs for details.", http.StatusInternalServerError) |
| 34 | glog.Errorf("apiserver panic'd on %v %v: %v\n%s\n", req.Method, req.RequestURI, err, debug.Stack()) |
| 35 | }) |
| 36 | |
| 37 | logger := httplog.NewLogged(req, &w) |
| 38 | defer logger.Log() |
| 39 | |
| 40 | // Dispatch to the internal handler |
| 41 | handler.ServeHTTP(w, req) |
| 42 | }) |
| 43 | } |