Skip to content

Instantly share code, notes, and snippets.

@greuze
Created February 26, 2015 16:16
Show Gist options
  • Save greuze/b3feaeac6f00d0688417 to your computer and use it in GitHub Desktop.
Save greuze/b3feaeac6f00d0688417 to your computer and use it in GitHub Desktop.
Force HTTP error in node.js requests
var http = require('http');
var request = require('request');
function forceHttpError(error) {
var originalHttpRequest = http.request;
// Monkey-patch the http.request method with
// our implementation
http.request = function (opts, cb) {
// Call the original implementation of http.request()
var req = originalHttpRequest(opts, cb);
// In next tick, simulate an error in the http module
process.nextTick(function () {
req.emit('error', error);
// Prevent Request from waiting for
// this request to finish
req.removeAllListeners('response');
// Properly close the current request
req.end();
})
// We must return this value to keep it
// consistent with original implementation
return req;
};
return originalHttpRequest;
}
function unforceHttpError(originalHttpRequest) {
http.request = originalHttpRequest;
}
function getUrl(url, cb) {
request(url, function (err, response, body) {
if (err) {
console.error('Error in GET %s: %s', url, err);
} else {
console.log('Successful GET %s...', body.toString().slice(0, 100));
}
return cb(err, body);
});
}
var o1 = forceHttpError(new Error('Forced error'));
getUrl('http://google.com', function(err, body) {
unforceHttpError(o1);
getUrl('http://google.com', function(err, body) {
var o2 = forceHttpError(new Error('Other forced error'));
getUrl('http://google.com', function(err, body) {
unforceHttpError(o2);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment