package middleware import ( "net/http" "git.linuxforward.com/byom/byom-gateway/errors" "github.com/gin-gonic/gin" ) // ErrorHandler handles errors and returns appropriate responses func ErrorHandler() gin.HandlerFunc { return func(c *gin.Context) { c.Next() if len(c.Errors) > 0 { err := c.Errors.Last().Err if appErr, ok := err.(*errors.AppError); ok { switch appErr.Type { case errors.ErrorTypeValidation: c.AbortWithStatusJSON(http.StatusBadRequest, appErr) case errors.ErrorTypeNotFound: c.AbortWithStatusJSON(http.StatusNotFound, appErr) case errors.ErrorTypeAuthorization: c.AbortWithStatusJSON(http.StatusUnauthorized, appErr) case errors.ErrorTypeConflict: c.AbortWithStatusJSON(http.StatusConflict, appErr) default: c.AbortWithStatusJSON(http.StatusInternalServerError, appErr) } return } c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{ "error": err.Error(), }) } } }