customerror.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "runtime"
  6. "strconv"
  7. "strings"
  8. "time"
  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. c.ClientIP(),
  34. p[2],
  35. )
  36. c.JSON(http.StatusOK, gin.H{
  37. "code": statusCode,
  38. "msg": p[2],
  39. })
  40. } else {
  41. c.JSON(http.StatusOK, gin.H{
  42. "code": 500,
  43. "msg": errStr,
  44. })
  45. }
  46. case runtime.Error:
  47. c.JSON(http.StatusOK, gin.H{
  48. "code": 500,
  49. "msg": errStr.Error(),
  50. })
  51. default:
  52. panic(err)
  53. }
  54. }
  55. }()
  56. c.Next()
  57. }