Fix HTTP error response body reporting
This commit is contained in:
1 parent
0b10a70924
commit
64692fecba
2 files changed
+61
-23
No files matched your search
@@ -0,0 +1,33 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { createSealClientForUrl } from "./factory.js";
|
||||
|
||||
const servers: Array<ReturnType<typeof Bun.serve>> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const server of servers.splice(0)) server.stop(true);
|
||||
});
|
||||
|
||||
describe("Seal HTTP client errors", () => {
|
||||
test("includes ky's parsed response body after the response stream is consumed", async () => {
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: () => new Response(JSON.stringify({
|
||||
error: {
|
||||
code: "error:common:invalid-parameter",
|
||||
message: "contentType 取值非法"
|
||||
}
|
||||
}), {
|
||||
status: 400,
|
||||
headers: { "content-type": "application/json" }
|
||||
})
|
||||
});
|
||||
servers.push(server);
|
||||
|
||||
await expect(
|
||||
createSealClientForUrl(`http://127.0.0.1:${server.port}`, "dummy-token").get("/")
|
||||
).rejects.toThrow(
|
||||
'Request failed with status code 400 Bad Request: GET http://127.0.0.1:' +
|
||||
`${server.port}/: {"error":{"code":"error:common:invalid-parameter","message":"contentType 取值非法"}}`
|
||||
);
|
||||
});
|
||||
});
|
||||
+28
-23
@@ -3,6 +3,32 @@ import { CorpConfig } from "../config/types.js";
|
||||
import { clearSealToken, getSealSessionForCorp } from "../auth/seal.js";
|
||||
import { resolveSealCustomHeaders } from "./request-headers.js";
|
||||
|
||||
function formatErrorData(data: unknown): string {
|
||||
if (data === undefined || data === null || data === "") return "";
|
||||
if (typeof data === "string") return data;
|
||||
try {
|
||||
return JSON.stringify(data);
|
||||
} catch {
|
||||
return String(data);
|
||||
}
|
||||
}
|
||||
|
||||
function withResponseBody(error: unknown): Error {
|
||||
if (!(error instanceof HTTPError)) return error as Error;
|
||||
const body = formatErrorData(error.data);
|
||||
if (body) error.message = `${error.message}: ${body}`;
|
||||
return error;
|
||||
}
|
||||
|
||||
function createBeforeErrorHook(corpId?: string) {
|
||||
return async ({ error }: { error: unknown }) => {
|
||||
if (corpId && error instanceof HTTPError && error.response.status === 401) {
|
||||
clearSealToken(corpId);
|
||||
}
|
||||
return withResponseBody(error);
|
||||
};
|
||||
}
|
||||
|
||||
export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
|
||||
const session = await getSealSessionForCorp(corp);
|
||||
|
||||
@@ -14,19 +40,7 @@ export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
|
||||
Authorization: `Bearer ${session.token}`
|
||||
},
|
||||
hooks: {
|
||||
beforeError: [
|
||||
async ({ error }) => {
|
||||
if (error instanceof HTTPError && error.response.status === 401) {
|
||||
clearSealToken(corp.id);
|
||||
}
|
||||
const body =
|
||||
error instanceof HTTPError
|
||||
? await error.response.text().catch(() => "")
|
||||
: "";
|
||||
error.message = `${error.message}${body ? `: ${body}` : ""}`;
|
||||
return error;
|
||||
}
|
||||
]
|
||||
beforeError: [createBeforeErrorHook(corp.id)]
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -50,16 +64,7 @@ export function createSealClientForUrl(
|
||||
Authorization: `Bearer ${token}`
|
||||
},
|
||||
hooks: {
|
||||
beforeError: [
|
||||
async ({ error }) => {
|
||||
const body =
|
||||
error instanceof HTTPError
|
||||
? await error.response.text().catch(() => "")
|
||||
: "";
|
||||
error.message = `${error.message}${body ? `: ${body}` : ""}`;
|
||||
return error;
|
||||
}
|
||||
]
|
||||
beforeError: [createBeforeErrorHook()]
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user