error_handler.go 981 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package middleware
  2. import (
  3. "net/http"
  4. "git.linuxforward.com/byom/byom-gateway/errors"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // ErrorHandler handles errors and returns appropriate responses
  8. func ErrorHandler() gin.HandlerFunc {
  9. return func(c *gin.Context) {
  10. c.Next()
  11. if len(c.Errors) > 0 {
  12. err := c.Errors.Last().Err
  13. if appErr, ok := err.(*errors.AppError); ok {
  14. switch appErr.Type {
  15. case errors.ErrorTypeValidation:
  16. c.AbortWithStatusJSON(http.StatusBadRequest, appErr)
  17. case errors.ErrorTypeNotFound:
  18. c.AbortWithStatusJSON(http.StatusNotFound, appErr)
  19. case errors.ErrorTypeAuthorization:
  20. c.AbortWithStatusJSON(http.StatusUnauthorized, appErr)
  21. case errors.ErrorTypeConflict:
  22. c.AbortWithStatusJSON(http.StatusConflict, appErr)
  23. default:
  24. c.AbortWithStatusJSON(http.StatusInternalServerError, appErr)
  25. }
  26. return
  27. }
  28. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
  29. "error": err.Error(),
  30. })
  31. }
  32. }
  33. }