customerror.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. "github.com/go-admin-team/go-admin-core/sdk/config"
  11. )
  12. const ERROR_MSG = "网络异常,请稍后重试"
  13. func CustomError(c *gin.Context) {
  14. defer func() {
  15. if err := recover(); err != nil {
  16. if c.IsAborted() {
  17. c.Status(200)
  18. }
  19. msg := ERROR_MSG
  20. switch errStr := err.(type) {
  21. case string:
  22. p := strings.Split(errStr, "#")
  23. if len(p) == 3 && p[0] == "CustomError" {
  24. statusCode, e := strconv.Atoi(p[1])
  25. if e != nil {
  26. break
  27. }
  28. c.Status(statusCode)
  29. fmt.Println(
  30. time.Now().Format("2006-01-02 15:04:05"),
  31. "[ERROR]",
  32. c.Request.Method,
  33. c.Request.URL,
  34. statusCode,
  35. c.Request.RequestURI,
  36. c.ClientIP(),
  37. p[2],
  38. )
  39. if config.ApplicationConfig.Mode == "dev" {
  40. msg = p[2]
  41. }
  42. c.JSON(http.StatusOK, gin.H{
  43. "code": statusCode,
  44. "msg": msg,
  45. })
  46. } else {
  47. if config.ApplicationConfig.Mode == "dev" {
  48. msg = errStr
  49. }
  50. c.JSON(http.StatusOK, gin.H{
  51. "code": 500,
  52. "msg": msg,
  53. })
  54. }
  55. case runtime.Error:
  56. if config.ApplicationConfig.Mode == "dev" {
  57. msg = errStr.Error()
  58. }
  59. c.JSON(http.StatusOK, gin.H{
  60. "code": 500,
  61. "msg": msg,
  62. })
  63. default:
  64. panic(err)
  65. }
  66. }
  67. }()
  68. c.Next()
  69. }