Skip to content

Commit

Permalink
refactor: make error handling tighter and safer
Browse files Browse the repository at this point in the history
  • Loading branch information
xpmatteo committed Feb 14, 2024
1 parent 65bf1b6 commit 0b6aa2e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 21 deletions.
12 changes: 8 additions & 4 deletions todo/list.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package todo

import (
"errors"
)
type UserError struct {
message string
}

var ErrorBadId = &UserError{"bad todoItemId"}

var ErrorBadId = errors.New("bad todoItemId")
func (ue *UserError) Error() string {
return ue.message
}

type Item struct {
Title string
Expand Down
31 changes: 14 additions & 17 deletions web/handlers.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package web

import (
"errors"
"github.com/xpmatteo/todomvc-golang/todo"
"html/template"
"log"
Expand Down Expand Up @@ -53,12 +52,8 @@ func NewItemHandler(templ *template.Template, repository Repository) http.Handle
model.Add(title, nil)
return nil
})
if errors.Is(err, todo.ErrorBadId) {
badRequest(w, err)
return
}
if err != nil {
internalServerError(w, err)
handleError(w, err)
return
}

Expand All @@ -83,19 +78,25 @@ func ToggleHandler(templ *template.Template, repository Repository) http.Handler
model, err := with(repository, func(model *todo.List) error {
return model.Toggle(id)
})
if errors.Is(err, todo.ErrorBadId) {
badRequest(w, err)
return
}
if err != nil {
internalServerError(w, err)
handleError(w, err)
return
}
vm := viewModel(model, r)
render(w, r, templ, vm)
})
}

//goland:noinspection GoTypeAssertionOnErrors
func handleError(w http.ResponseWriter, err error) {
switch err.(type) {
case *todo.UserError:
badRequest(w, err)
default:
internalServerError(w, err)
}
}

func EditHandler(templ *template.Template, repository Repository) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
Expand All @@ -113,12 +114,8 @@ func EditHandler(templ *template.Template, repository Repository) http.Handler {
model, err := with(repository, func(model *todo.List) error {
return model.Edit(id, title)
})
if errors.Is(err, todo.ErrorBadId) {
badRequest(w, err)
return
}
if err != nil {
internalServerError(w, err)
handleError(w, err)
return
}

Expand All @@ -144,7 +141,7 @@ func DestroyHandler(templ *template.Template, repository Repository) http.Handle
return model.Destroy(id)
})
if err != nil {
internalServerError(w, err)
handleError(w, err)
return
}

Expand Down

0 comments on commit 0b6aa2e

Please sign in to comment.