diff --git a/lib/chrome.js b/lib/chrome.js index b093d1e..704eaa7 100644 --- a/lib/chrome.js +++ b/lib/chrome.js @@ -12,12 +12,12 @@ const defaults = require('./defaults.js'); const devtools = require('./devtools.js'); class ProtocolError extends Error { - constructor(request, response) { + constructor(request, response, opts) { let {message} = response; if (response.data) { message += ` (${response.data})`; } - super(message); + super(message, opts); // attach the original response as well this.request = request; this.response = response; @@ -84,20 +84,27 @@ class Chrome extends EventEmitter { this._enqueueCommand(method, params, sessionId, callback); return undefined; } else { - return new Promise((fulfill, reject) => { + return this._sendPromise(method, params, sessionId); + } + } + + async _sendPromise(method, params, sessionId) { + try { + return await new Promise((fulfill, reject) => { this._enqueueCommand(method, params, sessionId, (error, response) => { if (error) { - const request = {method, params, sessionId}; - reject( - error instanceof Error - ? error // low-level WebSocket error - : new ProtocolError(request, response) - ); + reject({ error, response }); } else { fulfill(response); } }); }); + } catch (err) { + if (err instanceof Error) { + throw new Error('low-level WebSocket error', { cause: err }); + } + const request = { method, params, sessionId }; + throw new ProtocolError(request, err?.response, { cause: err?.error }); } }