From 15ca0ac078f8436e9a8164b735ad701442310814 Mon Sep 17 00:00:00 2001 From: Alessandro Pagnin Date: Tue, 10 Dec 2024 14:57:22 +0100 Subject: [PATCH] feat: add ParseError (#7) Co-authored-by: Jens Neuse --- parser.go | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/parser.go b/parser.go index 17f7fb0..bbdaf3a 100644 --- a/parser.go +++ b/parser.go @@ -9,6 +9,25 @@ import ( "github.com/wundergraph/astjson/fastfloat" ) +type ParseError struct { + Err error +} + +func (p *ParseError) Error() string { + if p == nil { + return "" + } + return p.Err.Error() +} + +func NewParseError(err error) *ParseError { + if err == nil { + return nil + } + + return &ParseError{Err: err} +} + // Parser parses JSON. // // Parser may be re-used for subsequent parsing. @@ -38,11 +57,11 @@ func (p *Parser) Parse(s string) (*Value, error) { v, tail, err := parseValue(b2s(p.b), p.c, 0) if err != nil { - return nil, fmt.Errorf("cannot parse JSON: %s; unparsed tail: %q", err, startEndString(tail)) + return nil, NewParseError(fmt.Errorf("cannot parse JSON: %s; unparsed tail: %q", err, startEndString(tail))) } tail = skipWS(tail) if len(tail) > 0 { - return nil, fmt.Errorf("unexpected tail: %q", startEndString(tail)) + return nil, NewParseError(fmt.Errorf("unexpected tail: %q", startEndString(tail))) } return v, nil } @@ -54,11 +73,11 @@ func (p *Parser) ParseWithoutCache(s string) (*Value, error) { v, tail, err := parseValue(b2s(p.b), p.c, 0) if err != nil { - return nil, fmt.Errorf("cannot parse JSON: %s; unparsed tail: %q", err, startEndString(tail)) + return nil, NewParseError(fmt.Errorf("cannot parse JSON: %s; unparsed tail: %q", err, startEndString(tail))) } tail = skipWS(tail) if len(tail) > 0 { - return nil, fmt.Errorf("unexpected tail: %q", startEndString(tail)) + return nil, NewParseError(fmt.Errorf("unexpected tail: %q", startEndString(tail))) } return v, nil }