recover.go 604 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package middleware
  2. import (
  3. "net/http"
  4. "ordonnance/logger"
  5. "runtime/debug"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func Recover(c *gin.Context) {
  9. defer func() {
  10. if r := recover(); r != nil {
  11. //打印错误堆栈信息
  12. logger.Infof("panic: %v\n", r)
  13. debug.PrintStack()
  14. //封装通用json返回
  15. c.JSON(http.StatusOK, gin.H{
  16. "code": 201,
  17. "msg": errorToString(r),
  18. "data": nil,
  19. })
  20. c.Abort()
  21. }
  22. }()
  23. c.Next()
  24. }
  25. // recover错误,转string
  26. func errorToString(r interface{}) string {
  27. switch v := r.(type) {
  28. case error:
  29. return v.Error()
  30. default:
  31. return r.(string)
  32. }
  33. }