Skip to content

Commit

Permalink
Add optional failure handler for XHR effect
Browse files Browse the repository at this point in the history
* This extends the options for handling `xhr.send()` failures, in
  the provided effect. It allows users to handle the exception
  thrown on calls to `send()` explicitly, making it more capable to
  handle or recover from network failure, or loss of service, if
  the users whishes to.
  • Loading branch information
olle committed Nov 18, 2019
1 parent ec3e3b7 commit 2eed726
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
11 changes: 10 additions & 1 deletion src/batteries.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ effector(
data,
onSuccess,
onError,
onFailure,
}) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
Expand Down Expand Up @@ -108,6 +109,14 @@ effector(
}
}
};
xhr.send(data);
try {
xhr.send(data);
} catch (e) {
if (onFailure) {
trigger(...onFailure, { error: e });
} else {
throw e;
}
}
},
);
18 changes: 17 additions & 1 deletion src/batteries.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,23 @@ import { connect } from "./connector";

jest.mock("./event");

let THROW_ERROR_ON_SEND = false;

let xhrs = [];
beforeEach(() => {
THROW_ERROR_ON_SEND = false;
xhrs = [];
trigger.mockClear();
});

window.XMLHttpRequest = function() {
let xhr = {
open: jest.fn(),
send: jest.fn(),
send: THROW_ERROR_ON_SEND
? () => {
throw THROW_ERROR_ON_SEND;
}
: jest.fn(),
setRequestHeader: jest.fn(),
};
// remember created xhr requests
Expand Down Expand Up @@ -125,6 +132,15 @@ describe("xhr effect", () => {
expect(trigger).toHaveBeenCalledTimes(1);
expect(trigger).toHaveBeenCalledWith("error", "foo", response);
});
it("triggers an event on failure", () => {
THROW_ERROR_ON_SEND = new Error("no soup for you!");
effect("xhr", {
onFailure: ["failure", "foo"],
});
expect(trigger).toHaveBeenCalledWith("failure", "foo", {
error: THROW_ERROR_ON_SEND,
});
});
it("ignores success if onSuccess is unset", () => {
effect("xhr", {});

Expand Down

0 comments on commit 2eed726

Please sign in to comment.