recoverhandler.go 456 B

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