recovery.go 704 B

1234567891011121314151617181920212223242526272829303132
  1. package blademaster
  2. import (
  3. "fmt"
  4. "net/http/httputil"
  5. "os"
  6. "runtime"
  7. "go-common/library/log"
  8. )
  9. // Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
  10. func Recovery() HandlerFunc {
  11. return func(c *Context) {
  12. defer func() {
  13. var rawReq []byte
  14. if err := recover(); err != nil {
  15. const size = 64 << 10
  16. buf := make([]byte, size)
  17. buf = buf[:runtime.Stack(buf, false)]
  18. if c.Request != nil {
  19. rawReq, _ = httputil.DumpRequest(c.Request, false)
  20. }
  21. pl := fmt.Sprintf("http call panic: %s\n%v\n%s\n", string(rawReq), err, buf)
  22. fmt.Fprintf(os.Stderr, pl)
  23. log.Error(pl)
  24. c.AbortWithStatus(500)
  25. }
  26. }()
  27. c.Next()
  28. }
  29. }