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

Error should not be thrown on HTTP error when noThrow is set. #123

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
19 changes: 18 additions & 1 deletion src/__tests__/fetchWithMiddleware-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ describe('fetchWithMiddleware', () => {
}
});

it('should not throw if noThrow set', async () => {
it('should not throw on GraphQL error if noThrow set', async () => {
fetchMock.mock({
matcher: '/graphql',
response: {
Expand All @@ -112,6 +112,23 @@ describe('fetchWithMiddleware', () => {
expect(res.errors).toEqual([{ location: 1, message: 'major error' }]);
});

it('should not throw on HTTP error if noThrow set', async () => {
fetchMock.mock({
matcher: '/graphql',
response: {
status: 500,
body: 'Something went completely wrong.',
},
method: 'POST',
});

const req = new RelayRequest(({}: any), {}, {}, null);

expect.assertions(1);
const res = await fetchWithMiddleware(req, [], [], true);
expect(res.status).toEqual(500);
});

it('should handle server non-2xx errors', async () => {
fetchMock.mock({
matcher: '/graphql',
Expand Down
8 changes: 5 additions & 3 deletions src/fetchWithMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,13 @@ function runFetch(req: RelayRequestAny): Promise<FetchResponse> {
}

// convert fetch response to RelayResponse object
const convertResponse: (next: MiddlewareRawNextFn) => MiddlewareNextFn = (next) => async (req) => {
const convertResponse: (noThrow?: boolean) => (next: MiddlewareRawNextFn) => MiddlewareNextFn = (
noThrow
) => (next) => async (req) => {
const resFromFetch = await next(req);

const res = await RelayResponse.createFromFetch(resFromFetch);
if (res.status && res.status >= 400) {
if (!noThrow && res.status && res.status >= 400) {
throw createRequestError(req, res);
}
return res;
Expand All @@ -44,7 +46,7 @@ export default function fetchWithMiddleware(
// $FlowFixMe
const wrappedFetch: MiddlewareNextFn = compose(
...middlewares,
convertResponse,
convertResponse(noThrow),
...rawFetchMiddlewares
)((runFetch: any));

Expand Down