Micro & pluggable web framework for Go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
990B

  1. // Copyright 2015 The Tango Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tango
  5. import (
  6. "bytes"
  7. "fmt"
  8. "net/http"
  9. "runtime"
  10. )
  11. // Recovery returns a middleware which catch panics and log them
  12. func Recovery(debug bool) HandlerFunc {
  13. return func(ctx *Context) {
  14. defer func() {
  15. if e := recover(); e != nil {
  16. var buf bytes.Buffer
  17. fmt.Fprintf(&buf, "Handler crashed with error: %v", e)
  18. for i := 1; ; i++ {
  19. _, file, line, ok := runtime.Caller(i)
  20. if !ok {
  21. break
  22. } else {
  23. fmt.Fprintf(&buf, "\n")
  24. }
  25. fmt.Fprintf(&buf, "%v:%v", file, line)
  26. }
  27. var content = buf.String()
  28. ctx.Logger.Error(content)
  29. if !ctx.Written() {
  30. if !debug {
  31. ctx.Result = InternalServerError(http.StatusText(http.StatusInternalServerError))
  32. } else {
  33. ctx.Result = InternalServerError(content)
  34. }
  35. }
  36. }
  37. }()
  38. ctx.Next()
  39. }
  40. }