From 2066da9ec719619aa3f1738d9d042c1155c36f3e Mon Sep 17 00:00:00 2001 From: Andrey Lushnikov Date: Fri, 16 Jun 2017 10:34:13 -0700 Subject: [PATCH] Page.evaluate should reject in case of evaluation error This patch makes Page.evaluate to throw an error if there was an error in evaluated code. --- lib/Page.js | 23 +++++++++++++++++++++-- test/test.js | 10 ++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/lib/Page.js b/lib/Page.js index 46307f90..39a0b14e 100644 --- a/lib/Page.js +++ b/lib/Page.js @@ -330,9 +330,10 @@ class Page extends EventEmitter { expression: code }); if (response.exceptionDetails) { - this._handleException(response.exceptionDetails); + await throwException(this._client, response.exceptionDetails); return; } + var remoteObject = response.result; if (remoteObject.type !== 'object') return remoteObject.value; @@ -347,11 +348,29 @@ class Page extends EventEmitter { objectId: remoteObject.objectId }); if (response.exceptionDetails) { - this._handleException(response.exceptionDetails); + await throwException(this._client, response.exceptionDetails); return; } return response.result.value; + + /** + * @param {!Object} exceptionDetails + * @return {!Promise} + */ + async function throwException(client, exceptionDetails) { + var exception = exceptionDetails.exception; + if (!exception) { + throw new Error('Evaluation failed with ' + exceptionDetails.text); + return; + } + var response = await client.send('Runtime.callFunctionOn', { + objectId: exception.objectId, + functionDeclaration: 'function() { return this.toString(); }', + returnByValue: true, + }); + throw new Error('Evaluation failed with ' + response.result.value); + } } /** diff --git a/test/test.js b/test/test.js index a07e9195..d0172d98 100644 --- a/test/test.js +++ b/test/test.js @@ -64,6 +64,16 @@ describe('Puppeteer', function() { }); expect(result).toBe(27); })); + it('should reject promise with exception', SX(async function() { + var error = null; + try { + await page.evaluate(() => not.existing.object.property); + } catch (e) { + error = e; + } + expect(error).toBeTruthy(); + expect(error.message).toContain('ReferenceError'); + })); }); it('Page Events: ConsoleMessage', SX(async function() {