Skip to content

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.

refactor: make crawling context strict and remove the error fallback

Martin Adámek8ce049ce2387
diff --git a/docs/upgrading/upgrading_v4.md b/docs/upgrading/upgrading_v4.md
index fb17ba055..a98b680e0 100644
--- a/docs/upgrading/upgrading_v4.md
+++ b/docs/upgrading/upgrading_v4.md
@@ -31,3 +31,11 @@ The crawler following options are removed:
- `handlePageFunction` -> `requestHandler`
- `handleRequestTimeoutSecs` -> `requestHandlerTimeoutSecs`
- `handleFailedRequestFunction` -> `failedRequestHandler`
+
+## Crawling context no longer includes Error for failed requests
+
+The crawling context no longer includes the `Error` object for failed requests. Use the second parameter of the `errorHandler` or `failedRequestHandler` callbacks to access the error.
+
+## Crawling context is strictly typed
+
+Previously, the crawling context extended a `Record` type, allowing to access any property. This was changed to a strict type, which means that you can only access properties that are defined in the context.
diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.ts
index d39b5c4b4..d59434e77 100644
--- a/packages/basic-crawler/src/internals/basic-crawler.ts
+++ b/packages/basic-crawler/src/internals/basic-crawler.ts
@@ -1803,9 +1803,7 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
if (shouldRetryRequest) {
await this.stats.errorTrackerRetry.addAsync(error, crawlingContext);
- await this._tagUserHandlerError(() =>
- this.errorHandler?.(this._augmentContextWithDeprecatedError(crawlingContext, error), error),
- );
+ await this.errorHandler?.(crawlingContext as LoadedContext<Context>, error);
if (error instanceof SessionError) {
await this._rotateSession(crawlingContext);
@@ -1866,9 +1864,7 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
this.log.error(`Request failed and reached maximum retries. ${message}`, { id, url, method, uniqueKey });
if (this.failedRequestHandler) {
- await this._tagUserHandlerError(() =>
- this.failedRequestHandler?.(this._augmentContextWithDeprecatedError(crawlingContext, error), error),
- );
+ await this.failedRequestHandler?.(crawlingContext as LoadedContext<Context>, error);
}
}
@@ -1916,19 +1912,13 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
return request.retryCount < maxRequestRetries;
}
- protected _augmentContextWithDeprecatedError(context: Context, error: Error) {
- Object.defineProperty(context, 'error', {
- get: () => {
- this.log.deprecated(
- "The 'error' property of the crawling context is deprecated, and it is now passed as the second parameter in 'errorHandler' and 'failedRequestHandler'. Please update your code, as this property will be removed in a future version.",
- );
-
- return error;
- },
- configurable: true,
- });
-
- return context as LoadedContext<Context>;
+ /**
+ * Updates handledRequestsCount from possibly stored counts, usually after worker migration.
+ */
+ protected async _loadHandledRequestCount(): Promise<void> {
+ if (this.requestManager) {
+ this.handledRequestsCount = await this.requestManager.handledCount();
+ }
}
protected async _executeHooks<HookLike extends (...args: any[]) => Awaitable<void>>(
diff --git a/test/core/crawlers/browser_crawler.test.ts b/test/core/crawlers/browser_crawler.test.ts
index 4a3c8a4a0..76145c853 100644
--- a/test/core/crawlers/browser_crawler.test.ts
+++ b/test/core/crawlers/browser_crawler.test.ts
@@ -1,5 +1,6 @@
import type { Server } from 'node:http';
-
+import { ENV_VARS } from '@apify/consts';
+import log from '@apify/log';
import { BROWSER_POOL_EVENTS, BrowserPool, OperatingSystemsName, PuppeteerPlugin } from '@crawlee/browser-pool';
import { BLOCKED_STATUS_CODES } from '@crawlee/core';
import type { PuppeteerCrawlingContext, PuppeteerGoToOptions, PuppeteerRequestHandler } from '@crawlee/puppeteer';
@@ -20,9 +21,6 @@ import puppeteer from 'puppeteer';
import { runExampleComServer } from 'test/shared/_helper.js';
import { MemoryStorageEmulator } from 'test/shared/MemoryStorageEmulator.js';
-import { ENV_VARS } from '@apify/consts';
-import log from '@apify/log';
-
import { BrowserCrawlerTest } from './basic_browser_crawler.js';
describe('BrowserCrawler', () => {
@@ -1270,7 +1268,6 @@ describe('BrowserCrawler', () => {
expect(crawlingContext.crawler.browserPool).toBeInstanceOf(BrowserPool);
expect(Object.hasOwn(crawlingContext, 'response')).toBe(true);
- expect(crawlingContext.error).toBeInstanceOf(Error);
expect(error).toBeInstanceOf(Error);
expect(error.message).toEqual('some error');
};
diff --git a/test/core/crawlers/cheerio_crawler.test.ts b/test/core/crawlers/cheerio_crawler.test.ts
index 43a5ac117..c31b9cada 100644
--- a/test/core/crawlers/cheerio_crawler.test.ts
+++ b/test/core/crawlers/cheerio_crawler.test.ts
@@ -1258,7 +1258,6 @@ describe('CheerioCrawler', () => {
expect(typeof crawlingContext.response).toBe('object');
expect(typeof crawlingContext.contentType).toBe('object');
- expect(crawlingContext.error).toBeInstanceOf(Error);
expect(error).toBeInstanceOf(Error);
expect(error.message).toEqual('some error');
};