go-zero/rest/handler/recoverhandler.go

24 lines
527 B
Go
Raw Normal View History

2020-07-29 18:00:04 +08:00
package handler
2020-07-26 17:09:05 +08:00
import (
"fmt"
"net/http"
"runtime/debug"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/rest/internal"
2020-07-26 17:09:05 +08:00
)
2021-03-01 19:15:35 +08:00
// RecoverHandler returns a middleware that recovers if panic happens.
2020-07-26 17:09:05 +08:00
func RecoverHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if result := recover(); result != nil {
2020-07-29 18:00:04 +08:00
internal.Error(r, fmt.Sprintf("%v\n%s", result, debug.Stack()))
2020-07-26 17:09:05 +08:00
w.WriteHeader(http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}