Skip to content

Commit

Permalink
Do not panic when invalid jsontype encountered
Browse files Browse the repository at this point in the history
fixes issue #6
  • Loading branch information
santhosh-tekuri committed Mar 22, 2018
1 parent 4eb6d64 commit 91ff43d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
8 changes: 8 additions & 0 deletions errors.go
Expand Up @@ -9,6 +9,14 @@ import (
"strings"
)

// InvalidJSONTypeError is the error type returned by ValidateInteface.
// this tells that specified go object is not valid jsonType.
type InvalidJSONTypeError string

func (e InvalidJSONTypeError) Error() string {
return fmt.Sprintf("invalid jsonType: %s", string(e))
}

// SchemaError is the error type returned by Compile.
type SchemaError struct {
// SchemaURL is the url to json-schema that filed to compile.
Expand Down
13 changes: 11 additions & 2 deletions schema.go
Expand Up @@ -99,7 +99,16 @@ func (s *Schema) Validate(r io.Reader) error {
//
// the doc must be the value decoded by json package using interface{} type.
// we recommend to use jsonschema.DecodeJSON(io.Reader) to decode JSON.
func (s *Schema) ValidateInterface(doc interface{}) error {
func (s *Schema) ValidateInterface(doc interface{}) (err error) {
defer func() {
if r := recover(); r != nil {
if _, ok := r.(InvalidJSONTypeError); ok {
err = r.(InvalidJSONTypeError)
} else {
panic(r)
}
}
}()
if err := s.validate(doc); err != nil {
finishSchemaContext(err, s)
finishInstanceContext(err)
Expand Down Expand Up @@ -446,7 +455,7 @@ func jsonType(v interface{}) string {
case map[string]interface{}:
return "object"
}
panic(fmt.Sprintf("unexpected jsonType: %T", v))
panic(InvalidJSONTypeError(fmt.Sprintf("%T", v)))
}

// equals tells if given two json values are equal or not.
Expand Down

0 comments on commit 91ff43d

Please sign in to comment.