onasty/internal/transport/http/apiv1/response.go (view raw)
| 1 | package apiv1 |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "log/slog" |
| 6 | "net/http" |
| 7 | |
| 8 | "github.com/gin-gonic/gin" |
| 9 | "github.com/olexsmir/onasty/internal/models" |
| 10 | ) |
| 11 | |
| 12 | var ErrUnauthorized = errors.New("unauthorized") |
| 13 | |
| 14 | type response struct { |
| 15 | Message string `json:"message"` |
| 16 | } |
| 17 | |
| 18 | func errorResponse(c *gin.Context, err error) { |
| 19 | if errors.Is(err, models.ErrUserEmailIsAlreadyInUse) || |
| 20 | errors.Is(err, models.ErrUsernameIsAlreadyInUse) || |
| 21 | errors.Is(err, models.ErrNoteContentIsEmpty) || |
| 22 | errors.Is(err, models.ErrNoteSlugIsAlreadyInUse) || |
| 23 | errors.Is(err, models.ErrUserIsNotActivated) || |
| 24 | errors.Is(err, models.ErrUserIsAlreeadyVerified) { |
| 25 | newError(c, http.StatusBadRequest, err.Error()) |
| 26 | return |
| 27 | } |
| 28 | |
| 29 | if errors.Is(err, models.ErrNoteExpired) { |
| 30 | newError(c, http.StatusGone, err.Error()) |
| 31 | return |
| 32 | } |
| 33 | |
| 34 | if errors.Is(err, models.ErrNoteNotFound) || |
| 35 | errors.Is(err, models.ErrVerificationTokenNotFound) { |
| 36 | newErrorStatus(c, http.StatusNotFound, err.Error()) |
| 37 | return |
| 38 | } |
| 39 | |
| 40 | if errors.Is(err, models.ErrUserNotFound) { |
| 41 | newErrorStatus(c, http.StatusBadRequest, err.Error()) |
| 42 | return |
| 43 | } |
| 44 | |
| 45 | if errors.Is(err, ErrUnauthorized) || |
| 46 | errors.Is(err, models.ErrUserWrongCredentials) { |
| 47 | newErrorStatus(c, http.StatusUnauthorized, err.Error()) |
| 48 | return |
| 49 | } |
| 50 | |
| 51 | newInternalError(c, err) |
| 52 | } |
| 53 | |
| 54 | func newError(c *gin.Context, status int, msg string) { |
| 55 | slog.ErrorContext(c.Request.Context(), msg, "status", status) |
| 56 | c.AbortWithStatusJSON(status, response{msg}) |
| 57 | } |
| 58 | |
| 59 | func newErrorStatus(c *gin.Context, status int, msg string) { |
| 60 | slog.ErrorContext(c.Request.Context(), msg, "status", status) |
| 61 | c.AbortWithStatus(status) |
| 62 | } |
| 63 | |
| 64 | func newInternalError(c *gin.Context, err error, msg ...string) { |
| 65 | slog.ErrorContext(c.Request.Context(), err.Error(), "status", "internal error") |
| 66 | |
| 67 | if len(msg) != 0 { |
| 68 | c.AbortWithStatusJSON(http.StatusInternalServerError, response{ |
| 69 | Message: msg[0], |
| 70 | }) |
| 71 | return |
| 72 | } |
| 73 | |
| 74 | c.AbortWithStatusJSON(http.StatusInternalServerError, response{ |
| 75 | Message: "internal error", |
| 76 | }) |
| 77 | } |