How to use rewriteError method in Puppeteer

Best JavaScript code snippet using puppeteer

Connection.js

Source:Connection.js Github

copy

Full Screen

...96 if (object.id && this._callbacks.has(object.id)) {97 const callback = this._callbacks.get(object.id);98 this._callbacks.delete(object.id);99 if (object.error)100 callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): ${object.error.message} ${object.error.data}`));101 else102 callback.resolve(object.result);103 } else {104 console.assert(!object.id);105 if (object.method === 'Target.receivedMessageFromTarget') {106 const session = this._sessions.get(object.params.sessionId);107 if (session)108 session._onMessage(object.params.message);109 } else if (object.method === 'Target.detachedFromTarget') {110 const session = this._sessions.get(object.params.sessionId);111 if (session)112 session._onClosed();113 this._sessions.delete(object.params.sessionId);114 } else {115 this.emit(object.method, object.params);116 }117 }118 }119 _onClose() {120 if (this._closeCallback) {121 this._closeCallback();122 this._closeCallback = null;123 }124 this._transport.removeAllListeners();125 // If transport throws any error at this point of time, we don't care and should swallow it.126 this._transport.on('error', () => {});127 for (const callback of this._callbacks.values())128 callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));129 this._callbacks.clear();130 for (const session of this._sessions.values())131 session._onClosed();132 this._sessions.clear();133 }134 dispose() {135 this._onClose();136 this._transport.close();137 }138 /**139 * @param {string} targetId140 * @return {!Promise<!CDPSession>}141 */142 async createSession(targetId) {143 const {sessionId} = await this.send('Target.attachToTarget', {targetId});144 const session = new CDPSession(this, targetId, sessionId);145 this._sessions.set(sessionId, session);146 return session;147 }148}149class CDPSession extends EventEmitter {150 /**151 * @param {!Connection} connection152 * @param {string} targetId153 * @param {string} sessionId154 */155 constructor(connection, targetId, sessionId) {156 super();157 this._lastId = 0;158 /** @type {!Map<number, {resolve: function, reject: function, error: !Error, method: string}>}*/159 this._callbacks = new Map();160 this._connection = connection;161 this._targetId = targetId;162 this._sessionId = sessionId;163 }164 /**165 * @param {string} method166 * @param {!Object=} params167 * @return {!Promise<?Object>}168 */169 send(method, params = {}) {170 if (!this._connection)171 return Promise.reject(new Error(`Protocol error (${method}): Session closed. Most likely the page has been closed.`));172 const id = ++this._lastId;173 const message = JSON.stringify({id, method, params});174 debugSession('SEND ► ' + message);175 this._connection.send('Target.sendMessageToTarget', {sessionId: this._sessionId, message}).catch(e => {176 // The response from target might have been already dispatched.177 if (!this._callbacks.has(id))178 return;179 const callback = this._callbacks.get(id);180 this._callbacks.delete(id);181 callback.reject(rewriteError(callback.error, e && e.message));182 });183 return new Promise((resolve, reject) => {184 this._callbacks.set(id, {resolve, reject, error: new Error(), method});185 });186 }187 /**188 * @param {string} message189 */190 _onMessage(message) {191 debugSession('◀ RECV ' + message);192 const object = JSON.parse(message);193 if (object.id && this._callbacks.has(object.id)) {194 const callback = this._callbacks.get(object.id);195 this._callbacks.delete(object.id);196 if (object.error)197 callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): ${object.error.message} ${object.error.data}`));198 else199 callback.resolve(object.result);200 } else {201 console.assert(!object.id);202 this.emit(object.method, object.params);203 }204 }205 async detach() {206 await this._connection.send('Target.detachFromTarget', {sessionId: this._sessionId});207 }208 _onClosed() {209 for (const callback of this._callbacks.values())210 callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));211 this._callbacks.clear();212 this._connection = null;213 }214}215helper.tracePublicAPI(CDPSession);216/**217 * @param {!Error} error218 * @param {string} message219 * @return {!Error}220 */221function rewriteError(error, message) {222 error.message = message;223 return error;224}...

Full Screen

Full Screen

crExecutionContext.js

Source:crExecutionContext.js Github

copy

Full Screen

...109 await (0, _crProtocolHelper.releaseObject)(this._client, objectId);110 }111}112exports.CRExecutionContext = CRExecutionContext;113function rewriteError(error) {114 if (error.message.includes('Object reference chain is too long')) return {115 result: {116 type: 'undefined'117 }118 };119 if (error.message.includes('Object couldn\'t be returned by value')) return {120 result: {121 type: 'undefined'122 }123 };124 if (error instanceof TypeError && error.message.startsWith('Converting circular structure to JSON')) (0, _stackTrace.rewriteErrorMessage)(error, error.message + ' Are you passing a nested JSHandle?');125 if (!js.isJavaScriptErrorInEvaluate(error) && !(0, _protocolError.isSessionClosedError)(error)) throw new Error('Execution context was destroyed, most likely because of a navigation.');126 throw error;127}...

Full Screen

Full Screen

ffExecutionContext.js

Source:ffExecutionContext.js Github

copy

Full Screen

...104function checkException(exceptionDetails) {105 if (!exceptionDetails) return;106 if (exceptionDetails.value) throw new js.JavaScriptErrorInEvaluate(JSON.stringify(exceptionDetails.value));else throw new js.JavaScriptErrorInEvaluate(exceptionDetails.text + (exceptionDetails.stack ? '\n' + exceptionDetails.stack : ''));107}108function rewriteError(error) {109 if (error.message.includes('cyclic object value') || error.message.includes('Object is not serializable')) return {110 result: {111 type: 'undefined',112 value: undefined113 }114 };115 if (error instanceof TypeError && error.message.startsWith('Converting circular structure to JSON')) (0, _stackTrace.rewriteErrorMessage)(error, error.message + ' Are you passing a nested JSHandle?');116 if (!js.isJavaScriptErrorInEvaluate(error) && !(0, _protocolError.isSessionClosedError)(error)) throw new Error('Execution context was destroyed, most likely because of a navigation.');117 throw error;118}119function potentiallyUnserializableValue(remoteObject) {120 const value = remoteObject.value;121 const unserializableValue = remoteObject.unserializableValue;122 return unserializableValue ? js.parseUnserializableValue(unserializableValue) : value;...

Full Screen

Full Screen

wkExecutionContext.js

Source:wkExecutionContext.js Github

copy

Full Screen

...40 });41 if (response.wasThrown) throw new js.JavaScriptErrorInEvaluate(response.result.description);42 return response.result.value;43 } catch (error) {44 throw rewriteError(error);45 }46 }47 async rawEvaluateHandle(expression) {48 try {49 const response = await this._session.send('Runtime.evaluate', {50 expression,51 contextId: this._contextId,52 returnByValue: false53 });54 if (response.wasThrown) throw new js.JavaScriptErrorInEvaluate(response.result.description);55 return response.result.objectId;56 } catch (error) {57 throw rewriteError(error);58 }59 }60 rawCallFunctionNoReply(func, ...args) {61 this._session.send('Runtime.callFunctionOn', {62 functionDeclaration: func.toString(),63 objectId: args.find(a => a instanceof js.JSHandle)._objectId,64 arguments: args.map(a => a instanceof js.JSHandle ? {65 objectId: a._objectId66 } : {67 value: a68 }),69 returnByValue: true,70 emulateUserGesture: true71 }).catch(() => {});72 }73 async evaluateWithArguments(expression, returnByValue, utilityScript, values, objectIds) {74 try {75 const response = await this._session.send('Runtime.callFunctionOn', {76 functionDeclaration: expression,77 objectId: utilityScript._objectId,78 arguments: [{79 objectId: utilityScript._objectId80 }, ...values.map(value => ({81 value82 })), ...objectIds.map(objectId => ({83 objectId84 }))],85 returnByValue,86 emulateUserGesture: true,87 awaitPromise: true88 });89 if (response.wasThrown) throw new js.JavaScriptErrorInEvaluate(response.result.description);90 if (returnByValue) return (0, _utilityScriptSerializers.parseEvaluationResultValue)(response.result.value);91 return utilityScript._context.createHandle(response.result);92 } catch (error) {93 throw rewriteError(error);94 }95 }96 async getProperties(context, objectId) {97 const response = await this._session.send('Runtime.getProperties', {98 objectId,99 ownProperties: true100 });101 const result = new Map();102 for (const property of response.properties) {103 if (!property.enumerable || !property.value) continue;104 result.set(property.name, context.createHandle(property.value));105 }106 return result;107 }108 createHandle(context, remoteObject) {109 const isPromise = remoteObject.className === 'Promise';110 return new js.JSHandle(context, isPromise ? 'promise' : remoteObject.subtype || remoteObject.type, renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject));111 }112 async releaseHandle(objectId) {113 await this._session.send('Runtime.releaseObject', {114 objectId115 });116 }117}118exports.WKExecutionContext = WKExecutionContext;119function potentiallyUnserializableValue(remoteObject) {120 const value = remoteObject.value;121 const isUnserializable = remoteObject.type === 'number' && ['NaN', '-Infinity', 'Infinity', '-0'].includes(remoteObject.description);122 return isUnserializable ? js.parseUnserializableValue(remoteObject.description) : value;123}124function rewriteError(error) {125 if (!js.isJavaScriptErrorInEvaluate(error) && !(0, _protocolError.isSessionClosedError)(error)) return new Error('Execution context was destroyed, most likely because of a navigation.');126 return error;127}128function renderPreview(object) {129 if (object.type === 'undefined') return 'undefined';130 if ('value' in object) return String(object.value);131 if (object.description === 'Object' && object.preview) {132 const tokens = [];133 for (const {134 name,135 value136 } of object.preview.properties) tokens.push(`${name}: ${value}`);137 return `{${tokens.join(', ')}}`;138 }...

Full Screen

Full Screen

ExecutionContext.js

Source:ExecutionContext.js Github

copy

Full Screen

...69 throw err;70 }71 const payload = await callFunctionPromise.catch(rewriteError);72 return createHandle(this, payload.result, payload.exceptionDetails);73 function rewriteError(error) {74 if (error.message.includes('Failed to find execution context with id'))75 throw new Error('Execution context was destroyed, most likely because of a navigation.');76 throw error;77 }78 }79 frame() {80 return this._frame;81 }82 async evaluate(pageFunction, ...args) {83 try {84 const handle = await this.evaluateHandle(pageFunction, ...args);85 const result = await handle.jsonValue();86 await handle.dispose();87 return result;...

Full Screen

Full Screen

logger.js

Source:logger.js Github

copy

Full Screen

2import RavenWinston from 'raven-winston'3import { merge } from 'lodash'4import VError from 'verror'5import config from './config/environment'6function rewriteError(level, msg, meta) {7 const output = {}8 if (meta instanceof Error) {9 output.err = {10 stack: VError.fullStack(meta),11 message: meta.message,12 extra: meta.extra,13 }14 return output15 }16 Object.assign(output, meta)17 if (meta.err) {18 output.err = {19 stack: VError.fullStack(meta.err),20 message: meta.err.message,...

Full Screen

Full Screen

main.js

Source:main.js Github

copy

Full Screen

...5import store from './store'6import {v4} from 'uuid';7Vue.prototype.$v4 = v4;8import rewriteError from './plugins/rewriteError'9rewriteError();10import 'iview/dist/styles/iview.css';11import {12 Button,13 ButtonGroup,14 Dropdown,15 DropdownItem,16 DropdownMenu,17 Input,18 Select,19 Option,20 Checkbox,21 CheckboxGroup,22 Page,23 Modal,...

Full Screen

Full Screen

httpError.js

Source:httpError.js Github

copy

Full Screen

...11 status: res?.statusCode || err.statusCode,12 headers: res?.headers || err.headers,13 body: res?.text || err.text14 }15 const nerror = rewriteError({16 code: base.code,17 status: base.status,18 statusMessage: res?.statusMessage || err.statusMessage19 })20 nerror.requestError = true21 nerror.code = base.code22 nerror.status = base.status23 nerror.headers = base.headers24 nerror.body = base.body25 return nerror...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 page.on('pageerror', error => {7 console.log(error.message);8 });9 await page.evaluate(() => {10 throw new Error('This is a page error');11 });12 await browser.close();13})();14const express = require('express');15const app = express();16app.use(express.static('public'));17app.get('/', (req, res) => {18 res.sendFile(__dirname + '/index.html');19});20app.listen(3000, () => {21 console.log('Server is listening on port 3000');22});23{24 "scripts": {25 },26 "dependencies": {27 }28}29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch({32 });33 const page = await browser.newPage();34 page.on('pageerror', error => {35 console.log(error.message);36 });37 await page.evaluate(() => {38 throw new Error('This is a page error');39 });40 await browser.close();41})();42const express = require('express');43const app = express();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await browser.close();6})();

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const browser = await puppeteer.launch();3 const page = await browser.newPage();4 page.on('error', err => {5 if (err.message.includes('net::ERR_ABORTED')) {6 console.log('net::ERR_ABORTED');7 }8 });9 await browser.close();10})();

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful