Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 52 additions & 42 deletions packages/basic-crawler/src/internals/basic-crawler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -959,45 +959,60 @@ export class BasicCrawler<

const crawlingContext = { request } as { request: Request } & Partial<CrawlingContext>;
try {
await this.basicContextPipeline
.chain(this.contextPipeline)
.call(crawlingContext, (ctx) => this.handleRequest(ctx, source, request));
} catch (error) {
// ContextPipelineInterruptedError means the request was intentionally skipped
// (e.g., doesn't match enqueue strategy after redirect). Just return gracefully.
if (error instanceof ContextPipelineInterruptedError) {
this.stats.discardJob(request.id || request.uniqueKey);
await this._timeoutAndRetry(
async () => this.requestManager?.markRequestAsHandled(request),
this.internalTimeoutMillis,
`Marking request ${crawlingContext.request.url} (${crawlingContext.request.id}) as handled timed out after ${
this.internalTimeoutMillis / 1e3
} seconds.`,
);
return;
}
try {
Comment on lines 961 to +962

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a semantic difference between try {} catch {} finally {} and try { try {} catch {} } finally {}? Can we simplify the syntax a little for better readability?

Image

await this.basicContextPipeline
.chain(this.contextPipeline)
.call(crawlingContext, (ctx) => this.handleRequest(ctx, source, request));
} catch (error) {
// ContextPipelineInterruptedError means the request was intentionally skipped
// (e.g., doesn't match enqueue strategy after redirect). Just return gracefully.
if (error instanceof ContextPipelineInterruptedError) {
this.stats.discardJob(request.id || request.uniqueKey);
await this._timeoutAndRetry(
async () => this.requestManager?.markRequestAsHandled(request),
this.internalTimeoutMillis,
`Marking request ${crawlingContext.request.url} (${crawlingContext.request.id}) as handled timed out after ${
this.internalTimeoutMillis / 1e3
} seconds.`,
);
return;
}

// If the error happened during pipeline initialization (e.g., navigation timeout, session/proxy error,
// i.e. not in user's requestHandler), handle it through the normal error flow.
const isPipelineError =
error instanceof ContextPipelineInitializationError || error instanceof SessionError;
if (isPipelineError) {
const unwrappedError = this.unwrapError(error);

await this._requestFunctionErrorHandler(
unwrappedError,
crawlingContext as CrawlingContext,
request,
this.requestManager!,
);
// SessionError already retired the session in `_requestFunctionErrorHandler`;
// skip `markBad` to avoid double-counting usage/error score.
if (!(unwrappedError instanceof SessionError)) {
crawlingContext.session?.markBad();
// If the error happened during pipeline initialization (e.g., navigation timeout, session/proxy error,
// i.e. not in user's requestHandler), handle it through the normal error flow.
const isPipelineError =
error instanceof ContextPipelineInitializationError || error instanceof SessionError;
if (isPipelineError) {
const unwrappedError = this.unwrapError(error);

await this._requestFunctionErrorHandler(
unwrappedError,
crawlingContext as CrawlingContext,
request,
this.requestManager!,
);
// SessionError already retired the session in `_requestFunctionErrorHandler`;
// skip `markBad` to avoid double-counting usage/error score.
if (!(unwrappedError instanceof SessionError)) {
crawlingContext.session?.markBad();
}
return;
}
return;
throw this.unwrapError(error);
}
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 () => {
Expand Down Expand Up @@ -1080,12 +1095,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) });
}
Expand Down
2 changes: 1 addition & 1 deletion test/core/crawlers/browser_crawler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
Loading