jsonparser icon indicating copy to clipboard operation
jsonparser copied to clipboard

Handle errors from ArrayEach callback

Open ProgramCpp opened this issue 8 years ago • 2 comments

Is there a way for the callback to ArrayEach to return errors.

_,errr := jsonparser.ArrayEach(bytes, func(... error) {
              return myerror
},...) 

if errr == myerror 

ProgramCpp avatar Nov 19 '17 11:11 ProgramCpp

You can declare an error variable above your ArrayEach block then assign it in your callback so you can check if nil afterwards.

Yokii908 avatar Apr 12 '18 15:04 Yokii908

@Yokii908 i've been using your approach, but wondering if there is a way to stop iteration on error? In my case, if I'm processing a large array and encounter an error, i would like to exit and return the error instead of continuing to iterate through a large array. Currently I do

var innererr error
_, err := jsonparser.ArrayEach(bytes, func(data []byte, _ jsonparser.ValueType, _ int, _ error) {
    // exit early if an error has already occurred
    if innererr != nil {
        return
    }

    // do heavy processing and set innererr if an error occurs
    if err := doHeavyWork(data); err != nil {
        innererr = err
        return
    }
}, "path", "to", "large", "array")

if there is a way to simply return the error and stop iteration, it's not obvious to me.

cludden avatar Aug 06 '18 20:08 cludden