{"record":{"id":"eacea4c0b977b7ba","repo":"apify/crawlee","slug":"failed-to-create-new-page-error-instanceof-erro","errorCode":null,"errorMessage":"Failed to create new page: ${error instanceof Error ? error.message : String(error)}","messagePattern":"Failed to create new page: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/stagehand-crawler/src/internals/stagehand-controller.ts","lineNumber":74,"sourceCode":"\n            const context = contexts[0];\n            const page = await context.newPage();\n\n            // Track active pages\n            page.once('close', () => {\n                this.activePages--;\n            });\n\n            try {\n                await this.waitForStagehandToRegisterPage(page);\n            } catch (error) {\n                await page.close().catch(() => {});\n                throw error;\n            }\n\n            return page;\n        } catch (error) {\n            throw new Error(`Failed to create new page: ${error instanceof Error ? error.message : String(error)}`, {\n                cause: error,\n            });\n        }\n    }\n\n    /**\n     * Waits until Stagehand knows about the page, so that `act()`/`extract()`/`observe()` can resolve it.\n     *\n     * Stagehand only learns about pages from CDP `Target.attachedToTarget` events on its own connection,\n     * and it maps them by main frame id. We create pages through a separate `connectOverCDP()` handle, so\n     * `context.newPage()` resolves before Stagehand has processed that event — the page is unresolvable for\n     * a short window, and the AI methods fail with 'Failed to resolve V3 Page from Playwright page'.\n     * Stagehand's own `newPage()` polls for the same reason.\n     */\n    private async waitForStagehandToRegisterPage(page: Page, timeoutMs = 10_000): Promise<void> {\n        const stagehand = this.getStagehand();\n        const mainFrameId = await this.getMainFrameId(page);\n        const deadline = Date.now() + timeoutMs;","sourceCodeStart":56,"sourceCodeEnd":92,"githubUrl":"https://github.com/apify/crawlee/blob/dbe57fb09ca607ad59dcf998f3925ef9ac3bb26c/packages/stagehand-crawler/src/internals/stagehand-controller.ts#L56-L92","documentation":"Generic wrapper for any error thrown inside StagehandController._newPage(). Every failure while creating a page (no context, context.newPage() failing, post-creation steps like waitForStagehandToRegisterPage throwing, cleanup page.close() races) is rethrown as 'Failed to create new page: <cause>' with the original error attached via { cause }.","triggerScenarios":"Any failure during new page creation: 'No browser context available', context.newPage() throwing (browser disconnected/crashed), or waitForStagehandToRegisterPage timing out ('Stagehand did not register the page within Nms').","commonSituations":"Debugging StagehandCrawler page-creation failures where the log only shows this wrapper — the actionable info is in the message suffix or err.cause.","solutions":["Inspect the interpolated message and err.cause to identify the root error, then fix that","If cause is a registration timeout, check that Stagehand can attach its CDP helper script (no conflicting extensions/interception)","If the browser crashed, restart the crawler / recycle the browser pool","Catch this in a requestHandler error path and retire the page so the pool can spawn a new one"],"exampleFix":"// before\nconst page = await browserPool.newPage(); // throws opaque wrapper\n// after\ntry {\n    const page = await browserPool.newPage();\n} catch (err) {\n    log.error('newPage failed', err.cause ?? err); // see root cause\n    throw err;\n}","handlingStrategy":"try-catch","validationCode":"const canCreate = browser?.isConnected?.() && browser.contexts().length > 0;\nif (!canCreate) throw new Error('skip newPage: browser not ready');","typeGuard":"const isWrappedPageError = (e) => e instanceof Error && e.message.startsWith('Failed to create new page:');","tryCatchPattern":"try {\n    const page = await browserPool.newPage();\n} catch (err) {\n    if (isWrappedPageError(err)) {\n        log.error('page creation failed', err.cause ?? err); // root cause in .cause\n        await browserPool.retireActiveBrowsers();\n    }\n    throw err;\n}","preventionTips":["Always inspect err.cause, not just the wrapper message","Keep browsers healthy (retire on disconnect)","Avoid custom timeouts shorter than Stagehand registration needs","Test page creation under browser-crash scenarios"],"tags":["stagehand","playwright","page-creation","error-wrapping"],"backgroundTag":"page-creation-failed","analyzedSha":"dbe57fb09ca607ad59dcf998f3925ef9ac3bb26c","analyzedAt":"2026-08-30T22:22:28.328Z","schemaVersion":2},"datasetVersion":"2026-08-30T23:17:21.991Z"}