How to use createProtocolError method in Puppeteer

Best JavaScript code snippet using puppeteer

Client.js

Source:Client.js Github

copy

Full Screen

...30 else {31 const errorMessage = this.hasFinishedOutput() ?32 'connection ended without disconnect receipt' :33 'connection ended unexpectedly';34 this.destroy(this.createProtocolError(errorMessage));35 }36 }37 _beforeSendResponse() {38 // No interception of outgoing frame39 }40 _onDestroyed(exception) {41 if (!exception) {42 return;43 }44 for (let key in this._subscriptions) {45 this._subscriptions[key].processMessageFrame(exception);46 }47 }48 /*49 * Create frame to send to the server. This method returns a Writable stream50 * object for sending the frame body content.51 */52 sendFrame(command, headers, options) {53 if (options) {54 let onReceipt = options.onReceipt;55 if (typeof options.onError === 'function') {56 const originalOnReceipt = onReceipt || function(){};57 const onError = options.onError;58 this.on('error', onError);59 onReceipt = () => {60 this.removeListener('error', onError);61 originalOnReceipt();62 };63 }64 if (typeof onReceipt === 'function') {65 const id = this._nextReceiptId++;66 this._receipts[id] = onReceipt;67 headers.receipt = id;68 }69 }70 return Socket.prototype.sendFrame.apply(this, arguments);71 }72 /*73 * Send CONNECT frame to the server.74 */75 connect(headers, callback) {76 if (typeof headers === 'string') {77 headers = {'host': headers};78 }79 headers = Object.assign({80 'accept-version': '1.0,1.1,1.2'81 }, headers);82 let heartbeat = this.getHeartbeat();83 if (typeof headers['heart-beat'] === "string") {84 const match = headers['heart-beat'].match(/^(\d+) *, *(\d+)$/);85 if (match) {86 heartbeat = [parseInt(match[1], 10), parseInt(match[2], 10)];87 this.setHeartbeat(heartbeat);88 }89 }90 headers['heart-beat'] = heartbeat[0] + "," + heartbeat[1];91 this.setCommandHandlers({92 'CONNECTED': onConnected,93 'ERROR': onError94 });95 if (typeof callback === 'function') {96 const self = this;97 (function() {98 const onConnected = function(client) {99 cleanup();100 callback(null, client);101 };102 const onError = function(error) {103 cleanup();104 callback(error);105 };106 const cleanup = function() {107 self.removeListener('error', onError);108 self.removeListener('connect', onConnected);109 };110 self.on('error', onError);111 self.on('connect', onConnected);112 })();113 }114 const frame = this.sendFrame('CONNECT', headers);115 frame.end();116 }117 /*118 * Send a message to the server. This method returns a Writable stream object 119 * for sending the frame body content.120 */121 send(headers, options) {122 if (typeof headers === 'string') {123 headers = {destination: headers};124 }125 return this.sendFrame('SEND', headers, options);126 }127 /*128 * Send a message with the specified body to the server.129 */130 sendString(headers, body, options, callback) {131 const frame = this.send(headers, options);132 frame.write(body);133 frame.end(callback);134 }135 begin(headers) {136 if (typeof headers !== 'object') {137 if (typeof headers !== 'undefined') {138 headers = {transaction: headers};139 }140 else {141 headers = {};142 }143 }144 if (!('transaction' in headers)) {145 headers.transaction = this._nextTransactionId++;146 }147 const transaction = new Transaction(headers.transaction, this);148 this.sendFrame('BEGIN', headers).end();149 return transaction;150 }151 subscribe(headers, messageListener) {152 if (typeof headers === 'string') {153 headers = {destination: headers};154 }155 let id = headers.id !== undefined ? 156 headers.id : this._nextSubcriptionId++;157 while (this._subscriptions[id] !== undefined) {158 id = this._nextSubcriptionId++;159 }160 headers.id = id;161 const ack = headers.ack || 'auto';162 ensureValidAckMode(ack);163 const subscription = new Subscription(id, ack, messageListener, this);164 this._subscriptions[id] = subscription;165 this.sendFrame('SUBSCRIBE', headers).end();166 return subscription;167 }168 _getAckHeaders(message, userHeaders) {169 return Object.assign({}, userHeaders, {170 'subscription': message.headers.subscription,171 'message-id': message.headers['message-id'],172 'id': message.headers.ack173 });174 }175 ack(message, headers, sendOptions, callback) {176 const frame = this.sendFrame('ACK',177 this._getAckHeaders(message, headers), sendOptions);178 frameHandler(frame, callback);179 }180 nack (message, headers, sendOptions, callback) {181 const frame = this.sendFrame('NACK',182 this._getAckHeaders(message, headers), sendOptions);183 frameHandler(frame, callback);184 }185 getSubscription(id) {186 return this._subscriptions[id];187 }188 setImplicitSubscription(id, ack, messageListener) {189 if (this._subscriptions.hasOwnProperty(id)) {190 throw new Error('subscription id \'' + id + '\' already in use');191 }192 if (ack === void 0 || ack === null){193 ack = 'auto';194 }195 ensureValidAckMode(ack);196 const subscription = new Subscription(id, ack, messageListener, this);197 this._subscriptions[id] = subscription;198 return subscription;199 }200 /*201 * Perform graceful disconnect from server. This operation does not complete202 * until all messages are acknowledged.203 */204 disconnect(callback) {205 if (typeof callback === 'function') {206 const self = this;207 (function() {208 const onEnd = function(client) {209 cleanup();210 callback(null, client);211 };212 const onError = function(error) {213 cleanup();214 callback(error);215 };216 const cleanup = function() {217 self.removeListener('end', onEnd);218 self.removeListener('error', onError);219 };220 self.on('end', onEnd);221 self.on('error', onError);222 })();223 }224 this.sendFrame('DISCONNECT', {}, {225 onReceipt: () => {226 this._hasDisconnectReceipt = true;227 const transport = this.getTransportSocket();228 if (this._resetDisconnect) {229 this.destroy();230 }231 else{232 transport.end();233 }234 }235 }).end(this._finishOutput.bind(this));236 // Keep the transport output open until the receipt is processed just in 237 // case the transport is not configured to handle half-open connections.238 this._disconnecting = true;239 }240 readEmptyBody(frame, callback) {241 frame.readEmptyBody((isEmpty) => {242 if (isEmpty) {243 if (typeof callback === 'function') {244 callback.call(this);245 }246 }247 else {248 this.destroy(this.createProtocolError('expected empty body frame'));249 }250 });251 }252 /*253 * Get the connection options that the client was initialized with.254 */255 getOptions() {256 return this._options;257 }258}259function ensureValidAckMode(mode) {260 const validAckModes = [261 'auto', 'client', 'client-individual'262 ];263 if (validAckModes.indexOf(mode) === -1) {264 throw new Error('invalid ack mode: \'' + mode + '\'');265 }266}267function frameHandler(frame, callback) {268 const cb = function (err) {269 if (typeof callback === 'function') {270 callback(err || new Error('The frame failed but no error was provided'));271 }272 };273 frame.on('error', cb);274 frame.end(function (err) {275 frame.removeListener('error', cb);276 if (typeof callback === 'function') {277 callback(err);278 }279 });280}281function onConnected(frame, beforeSendResponse) {282 // If no version header is present then assume the server is running stomp 1.0283 // protocol284 this.setVersion(frame.headers.version || '1.0');285 this.setCommandHandlers({286 'MESSAGE': onMessage,287 'RECEIPT': onReceipt,288 'ERROR': onError289 });290 this.readEmptyBody(frame, () => {291 if (frame.headers['heart-beat'] !== undefined) {292 const heartbeat = frame.headers['heart-beat']293 .split(',').map(function(x) {294 return parseInt(x, 10);295 });296 if ( heartbeat.length > 1 &&297 !isNaN(heartbeat[0]) &&298 !isNaN(heartbeat[1]) ) {299 this._runHeartbeat(heartbeat[0], heartbeat[1]);300 }301 }302 this.headers = frame.headers;303 this.emit('connect', this);304 beforeSendResponse();305 });306}307function onError(frame) {308 const message = frame.headers.message ? frame.headers.message :309 'server sent ERROR frame';310 const error = this.createApplicationError(message);311 if ( frame.headers['content-type'] === 'text/plain' &&312 frame.headers['content-length'] <= ERROR_MAX_CONTENT_LENGTH) {313 const content = new BufferWritable(Buffer.alloc(ERROR_MAX_CONTENT_LENGTH));314 frame.on('end', function() {315 error.longMessage = content.getWrittenSlice().toString();316 this.destroy(error);317 });318 frame.pipe(content);319 }320 else {321 this.destroy(error);322 }323}324function onMessage(frame, beforeSendResponse) {325 const subId = frame.headers.subscription;326 const subscription = this._subscriptions[subId];327 if (subscription === void 0) {328 this.destroy(this.createProtocolError('invalid subscription id ' + subId));329 return;330 }331 subscription.processMessageFrame(null, frame);332 beforeSendResponse();333}334function onReceipt(frame, beforeSendResponse) {335 const id = frame.headers['receipt-id'];336 if (id === undefined || this._receipts[id] === undefined) {337 this.destroy(this.createProtocolError('invalid receipt'));338 return;339 }340 this.readEmptyBody(frame, function() {341 this._receipts[id].call(this);342 delete this._receipts[id];343 beforeSendResponse();344 });345}346function onUnknownCommand(frame) {347 this.destroy(this.createProtocolError(348 'unknown command \'' + frame.command + '\''349 ));350}...

Full Screen

Full Screen

Connection.js

Source:Connection.js Github

copy

Full Screen

...121 // Callbacks could be all rejected if someone has called `.dispose()`.122 if (callback) {123 this._callbacks.delete(object.id);124 if (object.error)125 callback.reject(createProtocolError(callback.error, callback.method, object));126 else127 callback.resolve(object.result);128 }129 } else {130 this.emit(object.method, object.params);131 }132 }133 _onClose() {134 if (this._closed)135 return;136 this._closed = true;137 this._transport.onmessage = null;138 this._transport.onclose = null;139 for (const callback of this._callbacks.values())140 callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));141 this._callbacks.clear();142 for (const session of this._sessions.values())143 session._onClosed();144 this._sessions.clear();145 this.emit(Events.Connection.Disconnected);146 }147 dispose() {148 this._onClose();149 this._transport.close();150 }151 /**152 * @param {Protocol.Target.TargetInfo} targetInfo153 * @return {!Promise<!CDPSession>}154 */155 async createSession(targetInfo) {156 const {157 sessionId158 } = await this.send('Target.attachToTarget', {159 targetId: targetInfo.targetId,160 flatten: true161 });162 return this._sessions.get(sessionId);163 }164}165class CDPSession extends EventEmitter {166 /**167 * @param {!Connection} connection168 * @param {string} targetType169 * @param {string} sessionId170 */171 constructor(connection, targetType, sessionId) {172 super();173 /** @type {!Map<number, {resolve: function, reject: function, error: !Error, method: string}>}*/174 this._callbacks = new Map();175 this._connection = connection;176 this._targetType = targetType;177 this._sessionId = sessionId;178 }179 /**180 * @param {string} method181 * @param {!Object=} params182 * @return {!Promise<?Object>}183 */184 send(method, params = {}) {185 if (!this._connection)186 return Promise.reject(new Error(`Protocol error (${method}): Session closed. Most likely the ${this._targetType} has been closed.`));187 const id = this._connection._rawSend({188 sessionId: this._sessionId,189 method,190 params191 });192 return new Promise((resolve, reject) => {193 this._callbacks.set(id, {194 resolve,195 reject,196 error: new Error(),197 method198 });199 });200 }201 /**202 * @param {{id?: number, method: string, params: Object, error: {message: string, data: any}, result?: *}} object203 */204 _onMessage(object) {205 if (object.id && this._callbacks.has(object.id)) {206 const callback = this._callbacks.get(object.id);207 this._callbacks.delete(object.id);208 if (object.error)209 callback.reject(createProtocolError(callback.error, callback.method, object));210 else211 callback.resolve(object.result);212 } else {213 assert(!object.id);214 this.emit(object.method, object.params);215 }216 }217 async detach() {218 if (!this._connection)219 throw new Error(`Session already detached. Most likely the ${this._targetType} has been closed.`);220 await this._connection.send('Target.detachFromTarget', {221 sessionId: this._sessionId222 });223 }224 _onClosed() {225 for (const callback of this._callbacks.values())226 callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));227 this._callbacks.clear();228 this._connection = null;229 this.emit(Events.CDPSession.Disconnected);230 }231}232/**233 * @param {!Error} error234 * @param {string} method235 * @param {{error: {message: string, data: any}}} object236 * @return {!Error}237 */238function createProtocolError(error, method, object) {239 let message = `Protocol error (${method}): ${object.error.message}`;240 if ('data' in object.error)241 message += ` ${object.error.data}`;242 return rewriteError(error, message);243}244/**245 * @param {!Error} error246 * @param {string} message247 * @return {!Error}248 */249function rewriteError(error, message) {250 error.message = message;251 return error;252}...

Full Screen

Full Screen

wkConnection.js

Source:wkConnection.js Github

copy

Full Screen

...158 dispatchMessage(object) {159 if (object.id && this._callbacks.has(object.id)) {160 const callback = this._callbacks.get(object.id);161 this._callbacks.delete(object.id);162 if (object.error) callback.reject(createProtocolError(callback.error, callback.method, object.error));else callback.resolve(object.result);163 } else if (object.id && !object.error) {164 // Response might come after session has been disposed and rejected all callbacks.165 (0, _utils.assert)(this.isDisposed());166 } else {167 Promise.resolve().then(() => this.emit(object.method, object.params));168 }169 }170}171exports.WKSession = WKSession;172function createProtocolError(error, method, protocolError) {173 let message = `Protocol error (${method}): ${protocolError.message}`;174 if ('data' in protocolError) message += ` ${JSON.stringify(protocolError.data)}`;175 return (0, _stackTrace.rewriteErrorMessage)(error, message);...

Full Screen

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 const error = await page.evaluate(() => {6 const error = new Error('Custom error message');7 error.stack = 'Custom stack';8 return error;9 });10 const protocolError = await page.createCDPSession().createProtocolError(error);11 console.log(protocolError);12 await browser.close();13})();14{15}16const puppeteer = require('puppeteer');17(async () => {18 const browser = await puppeteer.launch();19 const page = await browser.newPage();20 const error = await page.evaluate(() => {21 const error = new Error('Custom error message');22 error.stack = 'Custom stack';23 return error;24 });25 const protocolError = await page.createCDPSession().createProtocolError(error);26 console.log(protocolError);27 await browser.close();28})();29{30}31const puppeteer = require('puppeteer');32(async () => {33 const browser = await puppeteer.launch();34 const page = await browser.newPage();35 const error = await page.evaluate(() => {36 const error = new Error('Custom error message');37 error.stack = 'Custom stack';38 return error;39 });40 const protocolError = await page.createCDPSession().createProtocolError(error);41 console.log(protocolError);42 await browser.close();43})();44{45}46const puppeteer = require('puppeteer');47(async () => {48 const browser = await puppeteer.launch();49 const page = await browser.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const browser = await puppeteer.launch({headless: false});3 const page = await browser.newPage();4 const client = await page.target().createCDPSession();5 await client.send('Network.enable');6 await client.send('Network.setRequestInterception', {patterns: [{urlPattern: '*'}]});7 client.on('Network.requestInterception', async ({requestId}) => {8 const error = await client.send('Network.createProtocolError', {9 });10 console.log(error);11 });12})();13 at CDPSession._onMessage (C:\Users\kshit\Desktop\puppeteer\puppeteer\lib\Connection.js:200:24)14 at Connection._onMessage (C:\Users\kshit\Desktop\puppeteer\puppeteer\lib\Connection.js:112:17)15 at emitOne (events.js:116:13)16 at WebSocket.emit (events.js:211:7)17 at Receiver._receiver.onmessage (C:\Users\kshit\Desktop\puppeteer\puppeteer\node_modules\ws\lib\WebSocket.js:143:47)18 at Receiver.dataMessage (C:\Users\kshit\Desktop\puppeteer\puppeteer\node_modules\ws\lib\Receiver.js:389:14)19 at Receiver.getData (C:\Users\kshit\Desktop\puppeteer\puppeteer\node_modules\ws\lib\Receiver.js:330:12)20 at Receiver.startLoop (C:\Users\kshit\Desktop\puppeteer\puppeteer\node_modules\ws\lib\Receiver.js:165:16)21 at Receiver.add (C:\Users\kshit\Desktop\puppeteer\puppeteer\node_modules\ws\lib\Receiver.js:139:10)22 at TLSSocket._ultron.on (C:\Users\kshit\Desktop\puppeteer\puppeteer\node_modules\ws\lib\WebSocket.js:138:22)

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