package httpx import ( "errors" "net/http" "github.com/gin-gonic/gin" ) type ErrorBody struct { Code string `json:"code"` Message string `json:"message"` } type ErrorResponse struct { Error ErrorBody `json:"error"` } type AppError struct { Status int Code string Message string } func (e *AppError) Error() string { return e.Message } func NewError(status int, code, message string) *AppError { return &AppError{Status: status, Code: code, Message: message} } func BadRequest(code, message string) *AppError { return NewError(http.StatusBadRequest, code, message) } func Unauthorized(code, message string) *AppError { return NewError(http.StatusUnauthorized, code, message) } func Forbidden(code, message string) *AppError { return NewError(http.StatusForbidden, code, message) } func NotFound(code, message string) *AppError { return NewError(http.StatusNotFound, code, message) } func Conflict(code, message string) *AppError { return NewError(http.StatusConflict, code, message) } func Internal(message string) *AppError { return NewError(http.StatusInternalServerError, "internal_error", message) } func Abort(c *gin.Context, err error) { var appErr *AppError if errors.As(err, &appErr) { c.AbortWithStatusJSON(appErr.Status, ErrorResponse{ErrorBody{appErr.Code, appErr.Message}}) return } c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorResponse{ErrorBody{"internal_error", "internal server error"}}) } func RespondError(c *gin.Context, err error) { var appErr *AppError if errors.As(err, &appErr) { c.JSON(appErr.Status, ErrorResponse{ErrorBody{appErr.Code, appErr.Message}}) return } c.JSON(http.StatusInternalServerError, ErrorResponse{ErrorBody{"internal_error", "internal server error"}}) }