Skip to content

Commit 8a3b555

Browse files
authored
Merge pull request #1908 from stalniy/main
Expose response details to error cause in HTTP client for better error diagnostics
2 parents 7272b3d + d87ae6d commit 8a3b555

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

packages/tendermint-rpc/src/rpcclients/http.spec.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,35 @@ describe("http", () => {
2929
).toBeRejectedWithError(/(ECONNREFUSED|Failed to fetch|fetch failed|(request to .* failed))/i);
3030
});
3131

32+
it("includes response in error cause for bad status codes", async () => {
33+
const originalFetch = globalThis.fetch;
34+
const mockResponse = {
35+
status: 404,
36+
statusText: "Not Found",
37+
ok: false,
38+
text: jasmine.createSpy("text").and.resolveTo("Not Found Error Body"),
39+
} as unknown as Response;
40+
41+
// Mock fetch to return a 404 response
42+
globalThis.fetch = jasmine.createSpy("fetch").and.resolveTo(mockResponse);
43+
44+
try {
45+
const error = await http("POST", "http://example.com", undefined, createJsonRpcRequest("health")).catch(
46+
(err) => err,
47+
);
48+
expect(error).toBeInstanceOf(Error);
49+
expect((error as Error).message).toContain("Bad status on response: 404");
50+
expect(error.cause).toEqual({
51+
status: 404,
52+
body: "Not Found Error Body",
53+
});
54+
expect(mockResponse.text).toHaveBeenCalled();
55+
} finally {
56+
// Restore original fetch
57+
globalThis.fetch = originalFetch;
58+
}
59+
});
60+
3261
(httpServerEnabled ? it : xit)("can POST to echo server with custom headers", async () => {
3362
// With custom headers
3463
const response = await http(

packages/tendermint-rpc/src/rpcclients/http.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
1-
function filterBadStatus(res: Response): Response {
1+
async function filterBadStatus(res: Response): Promise<Response> {
22
if (res.status >= 400) {
3-
throw new Error(`Bad status on response: ${res.status}`);
3+
const body = await res.text().catch(() => "Unable to retrieve body content");
4+
throw new Error(`Bad status on response: ${res.status}`, {
5+
cause: {
6+
status: res.status,
7+
body,
8+
},
9+
});
410
}
511
return res;
612
}

0 commit comments

Comments
 (0)