customerror.go 904 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "git.cestong.com.cn/cecf/config-center-server/common"
  9. "github.com/gin-gonic/gin"
  10. )
  11. func CustomError(c *gin.Context) {
  12. defer func() {
  13. if err := recover(); err != nil {
  14. if c.IsAborted() {
  15. c.Status(200)
  16. }
  17. switch errStr := err.(type) {
  18. case string:
  19. p := strings.Split(errStr, "#")
  20. if len(p) == 3 && p[0] == "CustomError" {
  21. statusCode, e := strconv.Atoi(p[1])
  22. if e != nil {
  23. break
  24. }
  25. c.Status(statusCode)
  26. fmt.Println(
  27. time.Now().Format("2006-01-02 15:04:05"),
  28. "[ERROR]",
  29. c.Request.Method,
  30. c.Request.URL,
  31. statusCode,
  32. c.Request.RequestURI,
  33. common.GetClientIP(c),
  34. p[2],
  35. )
  36. c.JSON(http.StatusOK, gin.H{
  37. "code": statusCode,
  38. "msg": p[2],
  39. })
  40. }
  41. default:
  42. panic(err)
  43. }
  44. }
  45. }()
  46. c.Next()
  47. }