| 1 |
/* |
| 2 |
Copyright 2013-2014 Canonical Ltd. |
| 3 |
|
| 4 |
This program is free software: you can redistribute it and/or modify it |
| 5 |
under the terms of the GNU General Public License version 3, as published |
| 6 |
by the Free Software Foundation. |
| 7 |
|
| 8 |
This program is distributed in the hope that it will be useful, but |
| 9 |
WITHOUT ANY WARRANTY; without even the implied warranties of |
| 10 |
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR |
| 11 |
PURPOSE. See the GNU General Public License for more details. |
| 12 |
|
| 13 |
You should have received a copy of the GNU General Public License along |
| 14 |
with this program. If not, see <http://www.gnu.org/licenses/>. |
| 15 |
*/ |
| 16 |
|
| 17 |
package api |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"net/http" |
| 22 |
|
| 23 |
"gitlab.com/ubports/development/core/lomiri-push-service/logger" |
| 24 |
) |
| 25 |
|
| 26 |
// PanicTo500Handler wraps another handler such that panics are recovered |
| 27 |
// and 500 reported. |
| 28 |
func PanicTo500Handler(h http.Handler, logger logger.Logger) http.Handler { |
| 29 |
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 30 |
defer func() { |
| 31 |
if err := recover(); err != nil { |
| 32 |
logger.PanicStackf("serving http: %v", err) |
| 33 |
// best effort |
| 34 |
w.Header().Set("Content-Type", "application/json") |
| 35 |
w.WriteHeader(500) |
| 36 |
fmt.Fprintf(w, `{"error":"internal","message":"INTERNAL SERVER ERROR"}`) |
| 37 |
} |
| 38 |
}() |
| 39 |
h.ServeHTTP(w, req) |
| 40 |
}) |
| 41 |
} |