Skip to content

Commit

Permalink
Merge pull request #7 from apify/hotfix/unhandled-exceptions
Browse files Browse the repository at this point in the history
Hotfix unhandled exceptions
  • Loading branch information
petrpatek authored Apr 7, 2021
2 parents dd213a0 + d200182 commit e2287eb
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ const { customOptionsHandler } = require('./handlers/custom-options');
const { browserHeadersHandler } = require('./handlers/browser-headers');
const { proxyHandler } = require('./handlers/proxy');

const isResponseOk = (response) => {
const { statusCode } = response;
const limitStatusCode = response.request.options.followRedirect ? 299 : 399;

return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304;
};

const mutableGot = got.extend({
// Must be mutable in order to override the defaults
// https://github.com/sindresorhus/got#instances
Expand All @@ -16,6 +23,18 @@ const mutableGot = got.extend({
// Custom header generator instance.
headerGenerator: new HeaderGenerator(),
},
// Got has issues with terminating requests and it can cause unhandled exceptions
hooks: {
afterResponse: [
(response) => {
if (isResponseOk(response)) {
response.request.destroy();
}

return response;
},
],
},
});

// Overriding the mutableGot defaults by merging its defaults and our scraping defaults.
Expand Down

0 comments on commit e2287eb

Please sign in to comment.