github.com/rohankumardubey/aresdb@v0.0.2-0.20190517170215-e54e3ca06b9c/api/panic_handler.go (about) 1 // Copyright (c) 2017-2018 Uber Technologies, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package api 16 17 import ( 18 "net/http" 19 ) 20 21 // PanicHandler is a wrapper handler for handling panic in http request handling 22 type PanicHandler struct { 23 handler http.Handler 24 } 25 26 // WithPanicHandling will apply panic handler to regular http handler. 27 func WithPanicHandling(handler http.Handler) PanicHandler { 28 return PanicHandler{ 29 handler: handler, 30 } 31 } 32 33 // ServeHTTP serves http request for PanicHandler. 34 func (handler PanicHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) { 35 defer func() { 36 if r := recover(); r != nil { 37 rw.WriteHeader(http.StatusInternalServerError) 38 switch e := r.(type) { 39 case error: 40 rw.Write([]byte(e.Error())) 41 case string: 42 rw.Write([]byte(e)) 43 default: 44 rw.Write([]byte("Unknown Panic")) 45 } 46 } 47 }() 48 handler.handler.ServeHTTP(rw, r) 49 }