package utils import ( "errors" "github.com/gofiber/fiber/v2" ) type ErrorCode string const ( ErrInternal ErrorCode = "INTERNAL_ERROR" ErrNotFound ErrorCode = "NOT_FOUND" ErrInvalidInput ErrorCode = "INVALID_INPUT" ErrForbidden ErrorCode = "FORBIDDEN" ErrUnauthorized ErrorCode = "UNAUTHORIZED" ) type Error struct { Code ErrorCode UserMessage string InternalError error StatusCode int } func (e *Error) Error() string { if e.InternalError != nil { return e.InternalError.Error() } return e.UserMessage } func (e *Error) Unwrap() error { return e.InternalError } func NewError(code ErrorCode, userMsg string, internalErr error) *Error { statusCode := fiber.StatusInternalServerError switch code { case ErrNotFound: statusCode = fiber.StatusNotFound case ErrInvalidInput: statusCode = fiber.StatusBadRequest case ErrInternal: statusCode = fiber.StatusInternalServerError case ErrForbidden: statusCode = fiber.StatusForbidden case ErrUnauthorized: statusCode = fiber.StatusUnauthorized } return &Error{ Code: code, UserMessage: userMsg, InternalError: internalErr, StatusCode: statusCode, } } func ErrorHandler(c *fiber.Ctx, err error) error { var e *Error if errors.As(err, &e) { return c.Status(e.StatusCode).JSON(fiber.Map{"message": e.UserMessage}) } return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "An unexpected error occurred"}) }