Skip to content

Commit

Permalink
refactor: make error handling simpler and more go-like
Browse files Browse the repository at this point in the history
  • Loading branch information
xpmatteo committed Feb 14, 2024
1 parent 0b6aa2e commit adc7466
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 14 deletions.
18 changes: 9 additions & 9 deletions todo/list.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package todo

type UserError struct {
message string
}

var ErrorBadId = &UserError{"bad todoItemId"}

func (ue *UserError) Error() string {
return ue.message
}
import (
"errors"
"fmt"
)

var (
UserError = errors.New("user error")
ErrorBadId = fmt.Errorf("%w: bad todoItemId", UserError)
)

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

import (
"errors"
"github.com/xpmatteo/todomvc-golang/todo"
"html/template"
"log"
Expand Down Expand Up @@ -87,12 +88,10 @@ func ToggleHandler(templ *template.Template, repository Repository) http.Handler
})
}

//goland:noinspection GoTypeAssertionOnErrors
func handleError(w http.ResponseWriter, err error) {
switch err.(type) {
case *todo.UserError:
if errors.Is(err, todo.UserError) {
badRequest(w, err)
default:
} else {
internalServerError(w, err)
}
}
Expand Down
2 changes: 1 addition & 1 deletion web/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ func Test_editHandler_elementNotFound(t *testing.T) {
EditHandler(templ, repository).ServeHTTP(w, r)

assert.Equal(http.StatusBadRequest, w.Code)
assert.Equal("bad todoItemId\n", w.Body.String())
assert.Equal("user error: bad todoItemId\n", w.Body.String())
}

func Test_toggleHandler_ok(t *testing.T) {
Expand Down

0 comments on commit adc7466

Please sign in to comment.