Skip to content

Commit

Permalink
fix: throw promise rejections on server errors
Browse files Browse the repository at this point in the history
  • Loading branch information
wescopeland committed Jun 17, 2023
1 parent 8eefc3e commit 32ccbd1
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/user/getUserSummary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,26 @@ describe("Function: getUserSummary", () => {
// ASSERT
expect(response).toEqual(mockExpectedSummaryValue);
});

it("given the API returns a 503, throws an error", async () => {
// ARRANGE
const authorization = buildAuthorization({
userName: "mockUserName",
webApiKey: "mockWebApiKey"
});

const mockResponse = "<html><body>the api is down</body></html>";

server.use(
rest.get(`${apiBaseUrl}/API_GetUserSummary.php`, (_, res, ctx) =>
res(ctx.status(503), ctx.body(mockResponse))
)
);

await expect(
getUserSummary(authorization, { userName: "WCopeland" })
).rejects.toThrow();
});
});

const mockGetUserSummaryResponse: GetUserSummaryResponse = {
Expand Down
17 changes: 17 additions & 0 deletions src/utils/internal/call.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,21 @@ describe("Util: call", () => {
expect(response).toEqual({ foo: "bar" });
expect(receivedMethod).toEqual("GET");
});

it("given the call returns an error, throws an error", async () => {
// ARRANGE
const mockRequestUrl = "https://abc.xyz/v1/endpoint2";

server.use(
rest.get(mockRequestUrl, (req, res, ctx) => {
return res(
ctx.status(503),
ctx.text("<HTML><BODY>something bad happened</BODY></HTML>")
);
})
);

// ASSERT
await expect(call({ url: mockRequestUrl })).rejects.toThrow();
});
});
7 changes: 7 additions & 0 deletions src/utils/internal/call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,12 @@ export const call = async <
const { url } = config;

const rawResponse = await unfetch(url);

if (!rawResponse.ok) {
throw new Error(
`HTTP Error: Status ${rawResponse.status} ${rawResponse.statusText}`
);
}

return (await rawResponse.json()) as T;
};

0 comments on commit 32ccbd1

Please sign in to comment.