Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
fix: Invoke deferred cleanup after error handling (#3876)
Jan Bucharde946038debb
diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.tsindex 07d0374d2..b613dd4cb 100644--- a/packages/basic-crawler/src/internals/basic-crawler.ts+++ b/packages/basic-crawler/src/internals/basic-crawler.ts@@ -1004,6 +1004,19 @@ export class BasicCrawler<return;}throw this.unwrapError(error);+ } finally {+ // Run request-scoped deferred cleanups only after the whole request lifecycle - including the user's error handler - has finished.+ const deferredCleanup =+ (crawlingContext as Partial<Record<typeof deferredCleanupKey, (() => Promise<unknown>)[]>>)[+ deferredCleanupKey+ ] ?? [];+ await Promise.all(+ deferredCleanup.map((fn) =>+ fn().catch((cleanupError) =>+ this.log.debug('Error in deferred cleanup', { error: cleanupError }),+ ),+ ),+ );}},isTaskReadyFunction: async () => {@@ -1086,12 +1099,7 @@ export class BasicCrawler<protected buildBasicContextPipeline(): ContextPipeline<{ request: Request }, CrawlingContext> {return ContextPipeline.create<{ request: Request }>().compose({ action: this.checkRobotsTxt.bind(this) })- .compose({- action: () => this.createBaseContext(),- cleanup: async (context) => {- await Promise.all(context[deferredCleanupKey].map((fn) => fn()));- },- })+ .compose({ action: () => this.createBaseContext() }).compose({ action: this.resolveSession.bind(this) }).compose({ action: this.createContextHelpers.bind(this) });}diff --git a/test/core/crawlers/browser_crawler.test.ts b/test/core/crawlers/browser_crawler.test.tsindex e27729e41..d7f207fd7 100644--- a/test/core/crawlers/browser_crawler.test.ts+++ b/test/core/crawlers/browser_crawler.test.ts@@ -349,7 +349,7 @@ describe('BrowserCrawler', () => {});// see https://github.com/apify/crawlee/issues/3873- test.skip('errorHandler has open page after non-timeout navigation error', async () => {+ test('errorHandler has open page after non-timeout navigation error', async () => {const puppeteerPlugin = new PuppeteerPlugin(puppeteer);const requestList = await RequestList.open({