github.com/lingyao2333/mo-zero@v1.4.1/rest/handler/recoverhandler.go (about)

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