recoverhandler.go 527 B

1234567891011121314151617181920212223
  1. package handler
  2. import (
  3. "fmt"
  4. "net/http"
  5. "runtime/debug"
  6. "github.com/tal-tech/go-zero/rest/internal"
  7. )
  8. // RecoverHandler returns a middleware that recovers if panic happens.
  9. func RecoverHandler(next http.Handler) http.Handler {
  10. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  11. defer func() {
  12. if result := recover(); result != nil {
  13. internal.Error(r, fmt.Sprintf("%v\n%s", result, debug.Stack()))
  14. w.WriteHeader(http.StatusInternalServerError)
  15. }
  16. }()
  17. next.ServeHTTP(w, r)
  18. })
  19. }