all repos

onasty @ 2cd7240

a one-time notes service

onasty/internal/transport/http/apiv1/response.go(view raw)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package apiv1

import (
	"errors"
	"log/slog"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/olexsmir/onasty/internal/models"
)

type response struct {
	Message string `json:"message"`
}

func errorResponse(c *gin.Context, err error) {
	if errors.Is(err, models.ErrUserEmailIsAlreadyInUse) ||
		errors.Is(err, models.ErrUsernameIsAlreadyInUse) {
		newError(c, http.StatusBadRequest, err.Error())
		return
	}

	if errors.Is(err, models.ErrUserNotFound) {
		newErrorStatus(c, http.StatusBadRequest, err.Error())
		return
	}

	if errors.Is(err, ErrUnauthorized) ||
		errors.Is(err, models.ErrUserWrongCredentials) {
		newErrorStatus(c, http.StatusUnauthorized, err.Error())
		return
	}

	newInternalError(c, err)
}

func newError(c *gin.Context, status int, msg string) { //nolint:unparam // TODO: remove me later
	slog.Error(msg, "status", status)
	c.AbortWithStatusJSON(status, response{msg})
}

func newErrorStatus(c *gin.Context, status int, msg string) {
	slog.Error(msg, "status", status)
	c.AbortWithStatus(status)
}

func newInternalError(c *gin.Context, err error, msg ...string) {
	slog.With("status", "internal error").Error(err.Error())

	if len(msg) != 0 {
		c.AbortWithStatusJSON(http.StatusInternalServerError, response{
			Message: msg[0],
		})
		return
	}

	c.AbortWithStatusJSON(http.StatusInternalServerError, response{
		Message: "internal error",
	})
}