customerror.go 839 B

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