Skip to content

Commit

Permalink
Adopt the official behavior of validateStatus and always return an er…
Browse files Browse the repository at this point in the history
…ror instance on rejection

Axios 0.19 introduced the validateStatus support. With `validateStatus: null`, the request should get resolved and not rejected.
https://github.com/axios/axios/blob/535d0c45c140cc2267612fcce019c1d65857be1d/lib/core/settle.js
  • Loading branch information
marcbachmann committed Apr 1, 2021
1 parent c4d95d7 commit 43e35b6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 19 deletions.
40 changes: 21 additions & 19 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,37 +114,39 @@ function purgeIfReplyOnce(mock, handler) {

function settle(resolve, reject, response, delay) {
if (delay > 0) {
setTimeout(function () {
settle(resolve, reject, response);
}, delay);
setTimeout(settle, delay, resolve, reject, response);
return;
}

if (response.config && response.config.validateStatus) {
response.config.validateStatus(response.status)
? resolve(response)
: reject(
createAxiosError(
"Request failed with status code " + response.status,
response.config,
response
)
);
// Support for axios < 0.13
if (!rejectWithError && (!response.config || !response.config.validateStatus)) {
if (response.status >= 200 && response.status < 300) {
resolve(response);
} else {
reject(response);
}
return;
}

// Support for axios < 0.11
if (response.status >= 200 && response.status < 300) {
if (
!response.config.validateStatus ||
response.config.validateStatus(response.status)
) {
resolve(response);
} else {
reject(response);
if (!rejectWithError) {
return reject(response);
}

reject(createAxiosError(
'Request failed with status code ' + response.status,
response.config,
response
));
}
}

function createAxiosError(message, config, response, code) {
// Support for axios < 0.13.0
if (!rejectWithError) return response;

var error = new Error(message);
error.isAxiosError = true;
error.config = config;
Expand Down
9 changes: 9 additions & 0 deletions test/basics.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,15 @@ describe("MockAdapter basics", function () {
});
});

it("supports providing a validateStatus null value", function () {
instance.defaults.validateStatus = null;
mock.onGet("/foo").reply(500);

return instance.get("/foo").then(function (response) {
expect(response.status).to.equal(500);
});
});

it("respects validatesStatus when requesting unhandled urls", function () {
instance.defaults.validateStatus = function () {
return true;
Expand Down

0 comments on commit 43e35b6

Please sign in to comment.