Skip to content

Commit

Permalink
add Error type and constants
Browse files Browse the repository at this point in the history
  • Loading branch information
tmus committed Aug 21, 2019
1 parent bae7fcf commit e1f3386
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 8 deletions.
12 changes: 12 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package validate

type Error string

const (
EmptyRuleset Error = "attempted to run a validator with an empty rule set"
ValidationFailed Error = "validation failed"
)

func (e Error) Error() string {
return string(e)
}
7 changes: 2 additions & 5 deletions validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package validate
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
)

Expand Down Expand Up @@ -48,10 +46,9 @@ func Make(r *http.Request, rule ...Rule) *Validator {
}

// Run determines if the given rules are satisfied by the request.
// A "perfect" outcome is `nil, nil`.
func (v *Validator) Run() (Message, error) {
if len(v.Rules) == 0 {
return nil, fmt.Errorf("no rules defined on validator")
return nil, EmptyRuleset
}

vm := make(Message)
Expand All @@ -63,7 +60,7 @@ func (v *Validator) Run() (Message, error) {
}

if len(vm) > 0 {
return vm, errors.New("validation failed")
return vm, ValidationFailed
}

return nil, nil
Expand Down
7 changes: 4 additions & 3 deletions validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,14 @@ func TestCheckCreatesValidatorAndRunsIt(t *testing.T) {
}
}

func TestMakeReturnsErrorWithNoRules(t *testing.T) {
func TestRunReturnsErrorIfNoRulesExist(t *testing.T) {
r, _ := http.NewRequest("GET", "localhost", nil)

validator := Make(r)

if _, err := validator.Run(); err == nil {
fmt.Println("no error returned from empty validator")
_, err := validator.Run()
if err != EmptyRuleset {
fmt.Println("expected `EmptyRuleset` error.")
t.FailNow()
}
}
Expand Down

0 comments on commit e1f3386

Please sign in to comment.