Skip to content

Commit cc64453

Browse files
authored
Fix error fallback for invalid JSON (#1546)
1 parent db6668f commit cc64453

File tree

4 files changed

+27
-4
lines changed

4 files changed

+27
-4
lines changed

Diff for: .changeset/quiet-seals-speak.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"openapi-fetch": patch
3+
---
4+
5+
Fix JSON consuming body

Diff for: packages/openapi-fetch/src/index.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -135,12 +135,12 @@ export default function createClient(clientOptions) {
135135
return { data: await response[parseAs](), response };
136136
}
137137

138-
// handle errors (always parse as .json() or .text())
139-
let error = {};
138+
// handle errors
139+
let error = await response.text();
140140
try {
141-
error = await response.json();
141+
error = JSON.parse(error); // attempt to parse as JSON
142142
} catch {
143-
error = await response.text();
143+
// noop
144144
}
145145
return { error, response };
146146
}

Diff for: packages/openapi-fetch/test/index.test.ts

+9
Original file line numberDiff line numberDiff line change
@@ -1141,6 +1141,15 @@ describe("client", () => {
11411141
expect(error.message).toBe("Error");
11421142
}
11431143
});
1144+
1145+
it("gracefully handles invalid JSON for errors", async () => {
1146+
const client = createClient<paths>();
1147+
mockFetchOnce({ status: 401, body: "Unauthorized" });
1148+
const { data, error } = await client.GET("/blogposts");
1149+
1150+
expect(data).toBeUndefined();
1151+
expect(error).toBe("Unauthorized");
1152+
});
11441153
});
11451154

11461155
describe("POST()", () => {

Diff for: packages/openapi-fetch/test/v7-beta.test.ts

+9
Original file line numberDiff line numberDiff line change
@@ -1136,6 +1136,15 @@ describe("client", () => {
11361136
expect(error.message).toBe("Error");
11371137
}
11381138
});
1139+
1140+
it("gracefully handles invalid JSON for errors", async () => {
1141+
const client = createClient<paths>();
1142+
mockFetchOnce({ status: 401, body: "Unauthorized" });
1143+
const { data, error } = await client.GET("/blogposts");
1144+
1145+
expect(data).toBeUndefined();
1146+
expect(error).toBe("Unauthorized");
1147+
});
11391148
});
11401149

11411150
describe("POST()", () => {

0 commit comments

Comments
 (0)