recover.go 766 B

123456789101112131415161718192021222324252627282930313233343536
  1. package middleware
  2. import (
  3. "go-nc/configs/global"
  4. "log"
  5. "net/http"
  6. "runtime/debug"
  7. "github.com/gin-gonic/gin"
  8. )
  9. func Recover(c *gin.Context) {
  10. defer func() {
  11. if r := recover(); r != nil {
  12. //打印错误堆栈信息
  13. log.Printf("panic: %v\n", r)
  14. global.App.Log.Error("panic: " + errorToString(r))
  15. debug.PrintStack()
  16. ErrorResponse(c, http.StatusInternalServerError, errorToString(r))
  17. //终止后续接口调用,不加的话recover到异常后,还会继续执行接口里后续代码
  18. c.Abort()
  19. }
  20. }()
  21. //加载完 defer recover,继续后续接口调用
  22. c.Next()
  23. }
  24. // recover错误,转string
  25. func errorToString(r interface{}) string {
  26. switch v := r.(type) {
  27. case error:
  28. return v.Error()
  29. default:
  30. return r.(string)
  31. }
  32. }