Skip to content

Commit

Permalink
give better errors on unexpected undefined objects
Browse files Browse the repository at this point in the history
First, if Evaluate finds one, give a helpful error instead of json's
unhelpful one.

Second, make JavascriptAttribute give a bit of context as part of its
error, so that the user can see what attribute caused the Evaluate
error.

Fixes #410.
  • Loading branch information
mvdan committed Aug 15, 2019
1 parent 232844a commit 519e0e1
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
8 changes: 8 additions & 0 deletions eval.go
Expand Up @@ -3,6 +3,7 @@ package chromedp
import (
"context"
"encoding/json"
"fmt"

"github.com/chromedp/cdproto/runtime"
)
Expand Down Expand Up @@ -63,6 +64,13 @@ func Evaluate(expression string, res interface{}, opts ...EvaluateOption) Evalua
return nil
}

if v.Type == "undefined" {
// The unmarshal above would fail with the cryptic
// "unexpected end of JSON input" error, so try to give
// a better one here.
return fmt.Errorf("encountered an undefined value")
}

// unmarshal
return json.Unmarshal(v.Value, res)
})
Expand Down
7 changes: 6 additions & 1 deletion query.go
Expand Up @@ -877,7 +877,12 @@ func JavascriptAttribute(sel interface{}, name string, res interface{}, opts ...
return fmt.Errorf("selector %q did not return any nodes", sel)
}

return EvaluateAsDevTools(snippet(attributeJS, cashX(true), sel, nodes[0], name), res).Do(ctx)
if err := EvaluateAsDevTools(
snippet(attributeJS, cashX(true), sel, nodes[0], name), res,
).Do(ctx); err != nil {
return fmt.Errorf("could not retrieve attribute %q: %v", name, err)
}
return nil
}, opts...)
}

Expand Down
15 changes: 15 additions & 0 deletions query_test.go
Expand Up @@ -502,6 +502,21 @@ func TestValue(t *testing.T) {
}
}

func TestValueUndefined(t *testing.T) {
t.Parallel()

ctx, cancel := testAllocate(t, "form.html")
defer cancel()

var value string
err := Run(ctx, Value("foo", &value, ByID))
want := `could not retrieve attribute "value": encountered an undefined value`
got := fmt.Sprint(err)
if !strings.Contains(got, want) {
t.Fatalf("want error %q, got %q", want, got)
}
}

func TestSetValue(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 519e0e1

Please sign in to comment.