Skip to content

Commit

Permalink
Improve the acceptable error
Browse files Browse the repository at this point in the history
Close #13.
  • Loading branch information
junhuif committed Jan 14, 2017
1 parent 46e77ae commit 559509c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 12 deletions.
16 changes: 7 additions & 9 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"log"
"net/http"
"net/url"
"reflect"
"regexp"

"github.com/gin-gonic/gin"
Expand All @@ -24,16 +23,15 @@ var (
// ErrRequestMissingAttrs error represents missing attributes error when create or update a resource
ErrRequestMissingAttrs = errors.New("couldn't bind resource")

// AcceptableError will be compared against the type of errors
// from `db.Create`. If the types match, Post will respond with
// AcceptableError will check the errors from `db.Create`.
// If the errors is acceptable, Post will respond with
// HTTPStatusUnprocessableEntity instead of panicking.
//
// This could be a lot smarter, but it was the simplest thing that
// supported my use-case at the time, without introducing more
// package dependencies.
AcceptableError reflect.Type
AcceptableError AcceptableErrorChecker = func(error) bool { return false }
)

// AcceptableErrorChecker checks whether the given error is acceptable.
type AcceptableErrorChecker func(err error) bool

var regexpID = regexp.MustCompile(`\d+`)

// DBModel defines an interface for ownership/authorisation when
Expand Down Expand Up @@ -166,7 +164,7 @@ func New(db *gorm.DB, single func() DBModel, collection func() interface{}, link
}

if err := db.Create(s).Error; err != nil {
if reflect.TypeOf(err) == AcceptableError {
if AcceptableError(err) {
ctx.JSON(HTTPStatusUnprocessableEntity, errToJSON(err))
} else {
panic(err)
Expand Down
5 changes: 2 additions & 3 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"net/http"
"net/http/httptest"
"os"
"reflect"
"strconv"
"strings"
"testing"
Expand Down Expand Up @@ -220,7 +219,7 @@ func TestPostWithAcceptableError(t *testing.T) {

resourceError = errors.New("acceptable error")

resources.AcceptableError = reflect.TypeOf(resourceError)
resources.AcceptableError = func(err error) bool { return err == resourceError }
defer clearResourceErrors()

res := req(postBody(t, body))
Expand Down Expand Up @@ -416,6 +415,6 @@ func assertNoErr(err error) {
}

func clearResourceErrors() {
resources.AcceptableError = nil
resources.AcceptableError = func(error) bool { return false }
resourceError = nil
}

0 comments on commit 559509c

Please sign in to comment.