recovery.go 661 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package tango
  2. import (
  3. "fmt"
  4. "net/http"
  5. "runtime"
  6. )
  7. func Recovery(debug bool) HandlerFunc {
  8. return func(ctx *Context) {
  9. defer func() {
  10. if e := recover(); e != nil {
  11. content := fmt.Sprintf("Handler crashed with error: %v", e)
  12. for i := 1; ;i += 1 {
  13. _, file, line, ok := runtime.Caller(i)
  14. if !ok {
  15. break
  16. } else {
  17. content += "\n"
  18. }
  19. content += fmt.Sprintf("%v %v", file, line)
  20. }
  21. ctx.Logger.Error(content)
  22. if !ctx.Written() {
  23. if !debug {
  24. content = http.StatusText(http.StatusInternalServerError)
  25. }
  26. ctx.Result = InternalServerError(content)
  27. }
  28. }
  29. }()
  30. ctx.Next()
  31. }
  32. }