Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use error-like #8504

Merged
merged 1 commit into from Jun 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Expand Up @@ -14,7 +14,7 @@ test-ts-types/**/dist/
package-lock.json
yarn.lock
/node6
/lib
lib
test/coverage.json
temp/
new-docs/
Expand Down
4 changes: 2 additions & 2 deletions src/common/BrowserConnector.ts
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

import { debugError } from '../common/helper.js';
import { debugError, isErrorLike } from '../common/helper.js';
import { isNode } from '../environment.js';
import { assert } from './assert.js';
import {
Expand Down Expand Up @@ -138,7 +138,7 @@ async function getWSEndpoint(browserURL: string): Promise<string> {
const data = await result.json();
return data.webSocketDebuggerUrl;
} catch (error) {
if (error instanceof Error) {
if (isErrorLike(error)) {
error.message =
`Failed to fetch browser webSocket URL from ${endpointURL}: ` +
error.message;
Expand Down
6 changes: 3 additions & 3 deletions src/common/FrameManager.ts
Expand Up @@ -16,7 +16,7 @@

import { EventEmitter } from './EventEmitter.js';
import { assert } from './assert.js';
import { helper, debugError } from './helper.js';
import { helper, debugError, isErrorLike } from './helper.js';
import { ExecutionContext, EVALUATION_SCRIPT_URL } from './ExecutionContext.js';
import {
LifecycleWatcher,
Expand Down Expand Up @@ -163,7 +163,7 @@ export class FrameManager extends EventEmitter {
} catch (error) {
// The target might have been closed before the initialization finished.
if (
error instanceof Error &&
isErrorLike(error) &&
(error.message.includes('Target closed') ||
error.message.includes('Session closed'))
) {
Expand Down Expand Up @@ -226,7 +226,7 @@ export class FrameManager extends EventEmitter {
? new Error(`${response.errorText} at ${url}`)
: null;
} catch (error) {
if (error instanceof Error) {
if (isErrorLike(error)) {
return error;
}
throw error;
Expand Down
7 changes: 4 additions & 3 deletions src/common/Page.ts
Expand Up @@ -43,7 +43,7 @@ import {
FrameManager,
FrameManagerEmittedEvents,
} from './FrameManager.js';
import { debugError, helper } from './helper.js';
import { debugError, helper, isErrorLike } from './helper.js';
import { HTTPRequest } from './HTTPRequest.js';
import { HTTPResponse } from './HTTPResponse.js';
import { Keyboard, Mouse, MouseButton, Touchscreen } from './Input.js';
Expand Down Expand Up @@ -1578,7 +1578,7 @@ export class Page extends EventEmitter {
const result = await pageBinding(...args);
expression = helper.pageBindingDeliverResultString(name, seq, result);
} catch (error) {
if (error instanceof Error)
if (isErrorLike(error))
expression = helper.pageBindingDeliverErrorString(
name,
seq,
Expand Down Expand Up @@ -2360,8 +2360,9 @@ export class Page extends EventEmitter {
timezoneId: timezoneId || '',
});
} catch (error) {
if (error instanceof Error && error.message.includes('Invalid timezone'))
if (isErrorLike(error) && error.message.includes('Invalid timezone')) {
throw new Error(`Invalid timezone ID: ${timezoneId}`);
}
throw error;
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/common/Tracing.ts
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/
import { assert } from './assert.js';
import { helper } from './helper.js';
import { helper, isErrorLike } from './helper.js';
import { CDPSession } from './Connection.js';

/**
Expand Down Expand Up @@ -122,7 +122,7 @@ export class Tracing {
const buffer = await helper.getReadableAsBuffer(readable, this._path);
resolve(buffer ?? undefined);
} catch (error) {
if (error instanceof Error) {
if (isErrorLike(error)) {
reject(error);
} else {
reject(new Error(`Unknown error: ${error}`));
Expand Down
20 changes: 19 additions & 1 deletion src/common/helper.ts
Expand Up @@ -165,7 +165,9 @@ async function waitForEvent<T>(
throw error;
}
);
if (result instanceof Error) throw result;
if (isErrorLike(result)) {
throw result;
}

return result;
}
Expand Down Expand Up @@ -378,6 +380,22 @@ async function getReadableFromProtocolStream(
});
}

interface ErrorLike extends Error {
name: string;
message: string;
}

export function isErrorLike(obj: unknown): obj is ErrorLike {
return obj instanceof Object && 'name' in obj && 'message' in obj;
}

export function isErrnoException(obj: unknown): obj is NodeJS.ErrnoException {
return (
isErrorLike(obj) &&
('errno' in obj || 'code' in obj || 'path' in obj || 'syscall' in obj)
);
}

export const helper = {
evaluationString,
pageBindingInitString,
Expand Down
9 changes: 5 additions & 4 deletions src/node/BrowserRunner.ts
Expand Up @@ -28,6 +28,8 @@ import {
helper,
debugError,
PuppeteerEventListener,
isErrorLike,
isErrnoException,
} from '../common/helper.js';
import { LaunchOptions } from './LaunchOptions.js';
import { Connection } from '../common/Connection.js';
Expand Down Expand Up @@ -216,7 +218,7 @@ export class BrowserRunner {
} catch (error) {
throw new Error(
`${PROCESS_ERROR_EXPLANATION}\nError cause: ${
error instanceof Error ? error.stack : error
isErrorLike(error) ? error.stack : error
}`
);
}
Expand Down Expand Up @@ -330,9 +332,8 @@ function pidExists(pid: number): boolean {
try {
return process.kill(pid, 0);
} catch (error) {
if (error instanceof Error) {
const err = error as NodeJS.ErrnoException;
if (err.code && err.code === 'ESRCH') {
if (isErrnoException(error)) {
if (error.code && error.code === 'ESRCH') {
return false;
}
}
Expand Down
18 changes: 9 additions & 9 deletions test/mocha-utils.ts
Expand Up @@ -14,24 +14,24 @@
* limitations under the License.
*/

import { TestServer } from '../utils/testserver/index.js';
import * as path from 'path';
import Protocol from 'devtools-protocol';
import expect from 'expect';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import rimraf from 'rimraf';
import sinon from 'sinon';
import puppeteer from '../lib/cjs/puppeteer/puppeteer.js';
import {
Browser,
BrowserContext,
} from '../lib/cjs/puppeteer/common/Browser.js';
import { isErrorLike } from '../lib/cjs/puppeteer/common/helper.js';
import { Page } from '../lib/cjs/puppeteer/common/Page.js';
import { PuppeteerNode } from '../lib/cjs/puppeteer/node/Puppeteer.js';
import utils from './utils.js';
import rimraf from 'rimraf';
import expect from 'expect';

import puppeteer from '../lib/cjs/puppeteer/puppeteer.js';
import { TestServer } from '../utils/testserver/index.js';
import { trackCoverage } from './coverage-utils.js';
import Protocol from 'devtools-protocol';
import utils from './utils.js';

const setupServer = async () => {
const assetsPath = path.join(__dirname, 'assets');
Expand Down Expand Up @@ -73,7 +73,7 @@ let extraLaunchOptions = {};
try {
extraLaunchOptions = JSON.parse(process.env['EXTRA_LAUNCH_OPTIONS'] || '{}');
} catch (error) {
if (error instanceof Error) {
if (isErrorLike(error)) {
console.warn(
`Error parsing EXTRA_LAUNCH_OPTIONS: ${error.message}. Skipping.`
);
Expand Down