Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mirror superagent behaviour in call back for creating errors #14

Merged
merged 5 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
28 changes: 26 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const http = require("http");
/**
* Add to the request prototype.
*/
Expand Down Expand Up @@ -90,13 +91,36 @@ function callback(err, res) {
return req._retry();
}, delay);
}

const fn = this._callback;
this.clearTimeout();

if (!err) {
try {
if (!this._isResponseOK(res)) {
let message = "Unsuccessful HTTP response";
if (res) {
message = http.STATUS_CODES[res.status] || message;
}

err = new Error(message);
err.status = res ? res.status : undefined;
}
} catch (e) {
err = e;
err.status = err.status || (res ? res.status : undefined);
repl-mike-roest marked this conversation as resolved.
Show resolved Hide resolved
}
}
if (!err) {
return fn(null, res);
}

err.response = res;

if (err) {
if (this._maxRetries) err.retries = this._retries - 1;
this.emit("error", err);
if (err && this.listeners("error").length > 0) {
this.emit("error", err);
repl-mike-roest marked this conversation as resolved.
Show resolved Hide resolved
}
}

fn(err, res);
Expand Down
11 changes: 8 additions & 3 deletions tests/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ describe("superagent-retry-delay", function () {
.end(function (err, res) {
res.status.should.eql(404);
requests.should.eql(3);
done(err);
err.response.status.should.eql(404);
err.message.should.eql("Not Found");
done();
});
});

Expand All @@ -100,7 +102,9 @@ describe("superagent-retry-delay", function () {
.end(function (err, res) {
res.status.should.eql(404);
requests.should.eql(3);
done(err);
err.response.status.should.eql(404);
err.message.should.eql("Not Found");
done();
});
});

Expand Down Expand Up @@ -428,7 +432,8 @@ describe("superagent-retry-delay", function () {
.end(function (err, res) {
res.text.should.eql("Misdirected Request");
requests.should.eql(2);
done(err);
err.message.should.eql("Misdirected Request");
done();
});
});

Expand Down