From d74d71dfa35a8bcfe36cb88bd2fb9d1e92a0ac37 Mon Sep 17 00:00:00 2001 From: "Gustavo L de Mello (Guz)" Date: Thu, 24 Oct 2024 19:53:38 -0300 Subject: [PATCH] feat(cookies,errors): error helper for cookie unmarshaling --- handlers/pages/dashboard.templ | 2 +- lib/cookies/cookies.go | 23 +++++++++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/handlers/pages/dashboard.templ b/handlers/pages/dashboard.templ index 35dd42a..11b52ee 100644 --- a/handlers/pages/dashboard.templ +++ b/handlers/pages/dashboard.templ @@ -33,7 +33,7 @@ func (p *Dashboard) ServeHTTP(w http.ResponseWriter, r *http.Request) { hasCookie := true var c DashboardCookie - if err := cookies.UnmarshalRequest(r, &c); errors.Is(err, cookies.ErrNoCookie) { + if err := cookies.UnmarshalRequest(r, &c); errors.Is(err, cookies.ErrNoCookie{}) { hasCookie = false c = DashboardCookie{Hello: "Hello world", Bool: true, Test: 69420} } else if err != nil { diff --git a/lib/cookies/cookies.go b/lib/cookies/cookies.go index db59860..0091254 100644 --- a/lib/cookies/cookies.go +++ b/lib/cookies/cookies.go @@ -10,6 +10,8 @@ import ( "strconv" "strings" "time" + + "forge.capytal.company/capytalcode/project-comicverse/lib/router/rerrors" ) type Marshaler interface { @@ -26,9 +28,16 @@ var ( ErrUnmarshal = errors.New("Failed to unmarshal JSON value from cookie value") ErrReflectPanic = errors.New("Reflect panic while trying to get tag from value") ErrMissingName = errors.New("Failed to get name of cookie") - ErrNoCookie = http.ErrNoCookie ) +type ErrNoCookie struct { + name string +} + +func (e ErrNoCookie) Error() string { + return fmt.Sprintf("Cookie \"%s\" missing from request", e.name) +} + var COOKIE_EXPIRE_VALID_FORMATS = []string{ time.DateOnly, time.DateTime, time.RFC1123, time.RFC1123Z, @@ -76,13 +85,23 @@ func UnmarshalRequest(r *http.Request, v any) error { } c, err := r.Cookie(name) - if err != nil { + if errors.Is(err, http.ErrNoCookie) { + return ErrNoCookie{name} + } else if err != nil { return err } return Unmarshal(c, v) } +func RerrUnmarshalCookie(err error) rerrors.RouteError { + if e, ok := err.(ErrNoCookie); ok { + return rerrors.MissingCookies([]string{e.name}) + } else { + return rerrors.InternalError(err) + } +} + func marshalValue(v any) (*http.Cookie, error) { b, err := json.Marshal(v) if err != nil {