39 lines
770 B
Go
39 lines
770 B
Go
package middleware
|
|
|
|
import (
|
|
models "api-service/internal/models"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// ErrorHandler handles errors globally
|
|
func ErrorHandler() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Next()
|
|
|
|
if len(c.Errors) > 0 {
|
|
err := c.Errors.Last()
|
|
status := http.StatusInternalServerError
|
|
|
|
// Determine status code based on error type
|
|
switch err.Type {
|
|
case gin.ErrorTypeBind:
|
|
status = http.StatusBadRequest
|
|
case gin.ErrorTypeRender:
|
|
status = http.StatusUnprocessableEntity
|
|
case gin.ErrorTypePrivate:
|
|
status = http.StatusInternalServerError
|
|
}
|
|
|
|
response := models.ErrorResponse{
|
|
Error: "internal_error",
|
|
Message: err.Error(),
|
|
Code: status,
|
|
}
|
|
|
|
c.JSON(status, response)
|
|
}
|
|
}
|
|
}
|