Skip to content

Commit

Permalink
add sentinel errors
Browse files Browse the repository at this point in the history
Add sentinel errors to allow easier checking of the type of error that
occurred during an operation.
  • Loading branch information
woodsbury committed Oct 3, 2024
1 parent bd4e5c5 commit 6538cb9
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
32 changes: 31 additions & 1 deletion errors.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
package jsonpointer

import "strconv"
import (
"errors"
"strconv"
)

var (
ErrArrayIndexOutOfBounds = errors.New("jsonpointer: array index out of bounds")
ErrInvalidArrayIndex = errors.New("jsonpointer: invalid array index")
ErrInvalidPointer = errors.New("jsonpointer: invalid pointer")
ErrValueNotFound = errors.New("jsonpointer: value not found")
)

type arrayIndexOutOfBoundsError struct {
index int
Expand All @@ -10,6 +20,10 @@ func (err *arrayIndexOutOfBoundsError) Error() string {
return "jsonpointer: array index out of bounds " + strconv.Itoa(err.index)
}

func (err *arrayIndexOutOfBoundsError) Is(target error) bool {
return target == ErrArrayIndexOutOfBounds
}

type invalidArrayIndexError struct {
tok string
}
Expand All @@ -18,6 +32,10 @@ func (err *invalidArrayIndexError) Error() string {
return "jsonpointer: invalid array index " + strconv.QuoteToASCII(err.tok)
}

func (err *invalidArrayIndexError) Is(target error) bool {
return target == ErrInvalidArrayIndex
}

type invalidPointerError struct {
ptr string
}
Expand All @@ -26,6 +44,10 @@ func (err *invalidPointerError) Error() string {
return "jsonpointer: invalid pointer " + strconv.QuoteToASCII(err.ptr)
}

func (err *invalidPointerError) Is(target error) bool {
return target == ErrInvalidPointer
}

type invalidTokenError struct {
tok string
}
Expand All @@ -34,10 +56,18 @@ func (err *invalidTokenError) Error() string {
return "jsonpointer: invalid token in pointer " + strconv.QuoteToASCII(err.tok)
}

func (err *invalidTokenError) Is(target error) bool {
return target == ErrInvalidPointer
}

type valueNotFoundError struct {
tok string
}

func (err *valueNotFoundError) Error() string {
return "jsonpointer: value not found " + strconv.QuoteToASCII(err.tok)
}

func (err *valueNotFoundError) Is(target error) bool {
return target == ErrValueNotFound
}
2 changes: 1 addition & 1 deletion get.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func (p Pointer) Get(value any) (any, error) {
}

refResult := reflect.ValueOf(result)
for i, tok = range p.tokens[i:] {
for _, tok = range p.tokens[i:] {
if err := getReflect(tok, &refResult); err != nil {
return nil, err
}
Expand Down

0 comments on commit 6538cb9

Please sign in to comment.