diff --git a/apps/web/app/api/agent/registrations/[id]/route.ts b/apps/web/app/api/agent/registrations/[id]/route.ts index 2c74f75c8..0dc0873e9 100644 --- a/apps/web/app/api/agent/registrations/[id]/route.ts +++ b/apps/web/app/api/agent/registrations/[id]/route.ts @@ -15,7 +15,11 @@ export async function DELETE(request: Request, { params }: { params: Promise<{ i const auth = await authenticateRequestRequireUser(request); if (!auth.success) return auth.response; const { id } = await params; - if (!UUID.test(id)) return Response.json({ error: "not_found" }, { status: 404 }); + if (!UUID.test(id)) + return Response.json( + { error: "not_found", message: "Connected agent not found" }, + { status: 404 } + ); try { const revoked = await revokeConnectedAgent(auth.userId, id); @@ -27,7 +31,10 @@ export async function DELETE(request: Request, { params }: { params: Promise<{ i }); return revoked ? new Response(null, { status: 204 }) - : Response.json({ error: "not_found" }, { status: 404 }); + : Response.json( + { error: "not_found", message: "Connected agent not found" }, + { status: 404 } + ); } catch (error) { reportError("DELETE /api/agent/registrations/[id] failed", error); return Response.json({ error: "Failed to disconnect the agent" }, { status: 500 }); diff --git a/apps/web/app/api/attachments/[id]/[index]/route.ts b/apps/web/app/api/attachments/[id]/[index]/route.ts index ff1be2bfc..4da851f91 100644 --- a/apps/web/app/api/attachments/[id]/[index]/route.ts +++ b/apps/web/app/api/attachments/[id]/[index]/route.ts @@ -35,7 +35,7 @@ export async function GET( return Response.json({ error: "invalid_link" }, { status: 403 }); } if (!isObjectStorageConfigured()) { - return Response.json({ error: "not_found" }, { status: 404 }); + return Response.json({ error: "not_found", message: "Attachment not found" }, { status: 404 }); } try { @@ -55,7 +55,10 @@ export async function GET( const attachment = email?.attachments[index]; // Gone with the email (retention, or deleted), or never stored. if (!email?.stored || !attachment) { - return Response.json({ error: "not_found" }, { status: 404 }); + return Response.json( + { error: "not_found", message: "Attachment not found" }, + { status: 404 } + ); } const location = await presignGet( attachmentKey(id, index), diff --git a/apps/web/app/api/endpoints/[slug]/requests/paginated/route.ts b/apps/web/app/api/endpoints/[slug]/requests/paginated/route.ts index 6bc2016c3..1bcdd0f1c 100644 --- a/apps/web/app/api/endpoints/[slug]/requests/paginated/route.ts +++ b/apps/web/app/api/endpoints/[slug]/requests/paginated/route.ts @@ -40,7 +40,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ slug }); if (!page) { - return Response.json({ error: "not_found" }, { status: 404 }); + return Response.json({ error: "not_found", message: "Endpoint not found" }, { status: 404 }); } return Response.json(extracts ? { ...page, items: await withEmailExtracts(page.items) } : page); diff --git a/apps/web/app/api/endpoints/[slug]/requests/route.ts b/apps/web/app/api/endpoints/[slug]/requests/route.ts index 5f28b8424..805565a98 100644 --- a/apps/web/app/api/endpoints/[slug]/requests/route.ts +++ b/apps/web/app/api/endpoints/[slug]/requests/route.ts @@ -45,7 +45,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ slug }); if (!data) { - return Response.json({ error: "not_found" }, { status: 404 }); + return Response.json({ error: "not_found", message: "Endpoint not found" }, { status: 404 }); } return Response.json(extracts ? await withEmailExtracts(data) : data); @@ -79,7 +79,7 @@ export async function DELETE(request: Request, { params }: { params: Promise<{ s }); if (!data) { - return Response.json({ error: "not_found" }, { status: 404 }); + return Response.json({ error: "not_found", message: "Endpoint not found" }, { status: 404 }); } return new Response(null, { status: 204 }); diff --git a/apps/web/app/api/integrations/google/connections/[id]/route.ts b/apps/web/app/api/integrations/google/connections/[id]/route.ts index 7201f6d78..c1e235104 100644 --- a/apps/web/app/api/integrations/google/connections/[id]/route.ts +++ b/apps/web/app/api/integrations/google/connections/[id]/route.ts @@ -15,7 +15,11 @@ export async function DELETE(request: Request, { params }: { params: Promise<{ i const { id } = await params; try { const token = await deleteGoogleConnection(auth.userId, id); - if (token === null) return Response.json({ error: "not_found" }, { status: 404 }); + if (token === null) + return Response.json( + { error: "not_found", message: "Google connection not found" }, + { status: 404 } + ); await revokeToken(token); await auditUserAction(request, auth.userId, { action: "integration.google_disconnected", diff --git a/apps/web/app/api/integrations/google/pick/route.ts b/apps/web/app/api/integrations/google/pick/route.ts index fcc92050a..d76aa000c 100644 --- a/apps/web/app/api/integrations/google/pick/route.ts +++ b/apps/web/app/api/integrations/google/pick/route.ts @@ -46,7 +46,8 @@ export async function POST(request: Request) { const connection = (await listGoogleConnections(auth.userId)).find( (candidate) => candidate.id === body.connectionId ); - if (!connection) return reply({ error: "not_found" }, 404); + if (!connection) + return reply({ error: "not_found", message: "Google connection not found" }, 404); const site = parseSite(request.headers.get(SITE_HEADER)); return reply({ url: pickerUrl(config, site, body.nonce, connection.email) }); } catch (error) { diff --git a/apps/web/app/api/request-shares/[id]/route.ts b/apps/web/app/api/request-shares/[id]/route.ts index d92370cc0..ce8f8231e 100644 --- a/apps/web/app/api/request-shares/[id]/route.ts +++ b/apps/web/app/api/request-shares/[id]/route.ts @@ -10,7 +10,8 @@ export async function DELETE(request: Request, { params }: { params: Promise<{ i if (!auth.success) return auth.response; const { id } = await params; - if (!isUuid(id)) return Response.json({ error: "not_found" }, { status: 404 }); + if (!isUuid(id)) + return Response.json({ error: "not_found", message: "Share link not found" }, { status: 404 }); try { const deleted = await deleteRequestShare(auth.userId, id); @@ -19,7 +20,11 @@ export async function DELETE(request: Request, { params }: { params: Promise<{ i status: deleted ? 200 : 404, targetId: id, }); - if (!deleted) return Response.json({ error: "not_found" }, { status: 404 }); + if (!deleted) + return Response.json( + { error: "not_found", message: "Share link not found" }, + { status: 404 } + ); return new Response(null, { status: 204 }); } catch (error) { reportError("Failed to revoke request share", error); diff --git a/apps/web/app/api/requests/[id]/attachments/[index]/route.ts b/apps/web/app/api/requests/[id]/attachments/[index]/route.ts index 816105ab6..d90975cb6 100644 --- a/apps/web/app/api/requests/[id]/attachments/[index]/route.ts +++ b/apps/web/app/api/requests/[id]/attachments/[index]/route.ts @@ -22,10 +22,14 @@ export async function GET( try { const record = await getRequestByIdForUser(auth.userId, id); - if (!record) return Response.json({ error: "not_found" }, { status: 404 }); + if (!record) + return Response.json({ error: "not_found", message: "Request not found" }, { status: 404 }); const attachment = record.email?.attachments[index]; if (record.kind !== "email" || !attachment) { - return Response.json({ error: "not_found" }, { status: 404 }); + return Response.json( + { error: "not_found", message: "Attachment not found" }, + { status: 404 } + ); } if (!record.email?.stored || !isObjectStorageConfigured()) { return Response.json( @@ -34,7 +38,11 @@ export async function GET( ); } const object = await getObject(attachmentKey(record.id, index)); - if (!object?.body) return Response.json({ error: "not_found" }, { status: 404 }); + if (!object?.body) + return Response.json( + { error: "not_found", message: "Attachment not found" }, + { status: 404 } + ); const length = object.headers.get("content-length"); return new Response(object.body, { headers: { diff --git a/apps/web/app/api/requests/[id]/raw/route.ts b/apps/web/app/api/requests/[id]/raw/route.ts index b9205bd33..de46a3db7 100644 --- a/apps/web/app/api/requests/[id]/raw/route.ts +++ b/apps/web/app/api/requests/[id]/raw/route.ts @@ -20,7 +20,8 @@ export async function GET(request: Request, { params }: { params: Promise<{ id: const { id } = await params; try { const record = await getRequestByIdForUser(auth.userId, id); - if (!record) return Response.json({ error: "not_found" }, { status: 404 }); + if (!record) + return Response.json({ error: "not_found", message: "Request not found" }, { status: 404 }); if (record.kind !== "email" || !record.email) { return Response.json({ error: "not_an_email" }, { status: 400 }); } diff --git a/apps/web/app/api/requests/[id]/render/route.ts b/apps/web/app/api/requests/[id]/render/route.ts index eee2217b5..590f6d1a9 100644 --- a/apps/web/app/api/requests/[id]/render/route.ts +++ b/apps/web/app/api/requests/[id]/render/route.ts @@ -52,11 +52,11 @@ export async function POST(request: Request, { params }: { params: Promise<{ id: if (key !== undefined && key !== null && (typeof key !== "string" || key.length > 200)) { return reply({ error: "mailgunSigningKey is text of at most 200 characters." }, 400); } - if (!isUuid(id)) return reply({ error: "not_found" }, 404); + if (!isUuid(id)) return reply({ error: "not_found", message: "Request not found" }, 404); try { const captured = await getRequestByIdForUser(auth.userId, id); - if (!captured) return reply({ error: "not_found" }, 404); + if (!captured) return reply({ error: "not_found", message: "Request not found" }, 404); if (captured.kind !== "email" || !captured.email) { return reply({ error: "Only a captured email can be rendered in a provider's shape." }, 400); } diff --git a/apps/web/app/api/requests/[id]/replay/route.ts b/apps/web/app/api/requests/[id]/replay/route.ts index c1699c048..769f7b4b3 100644 --- a/apps/web/app/api/requests/[id]/replay/route.ts +++ b/apps/web/app/api/requests/[id]/replay/route.ts @@ -20,7 +20,8 @@ export async function POST(request: Request, { params }: { params: Promise<{ id: const reply = (body: unknown, status = 200) => applyRateLimitHeaders(Response.json(body, { status }), rateLimit); - if (!/^[0-9a-f-]{36}$/i.test(id)) return reply({ error: "not_found" }, 404); + if (!/^[0-9a-f-]{36}$/i.test(id)) + return reply({ error: "not_found", message: "Request not found" }, 404); try { const { data, error } = await createAdminClient() .from("requests") @@ -32,10 +33,12 @@ export async function POST(request: Request, { params }: { params: Promise<{ id: endpoints: { user_id: string | null; slug: string }; }>(); if (error) throw error; - if (!data || data.endpoints.user_id !== auth.userId) return reply({ error: "not_found" }, 404); + if (!data || data.endpoints.user_id !== auth.userId) + return reply({ error: "not_found", message: "Request not found" }, 404); // Past retention it is gone, whether or not the cleanup has deleted it yet. const retained = await getRetainedRequestsByIds(data.endpoint_id, [data.id]); - if (retained.length === 0) return reply({ error: "not_found" }, 404); + if (retained.length === 0) + return reply({ error: "not_found", message: "Request not found" }, 404); const queued = await replayRequests(data.endpoint_id, [data.id]); await auditUserAction(request, auth.userId, { action: "request.replayed", diff --git a/apps/web/app/api/requests/[id]/route.ts b/apps/web/app/api/requests/[id]/route.ts index b1cee8de6..c56998024 100644 --- a/apps/web/app/api/requests/[id]/route.ts +++ b/apps/web/app/api/requests/[id]/route.ts @@ -19,7 +19,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ id: try { const data = await getRequestByIdForUser(auth.userId, id); if (!data) { - return Response.json({ error: "not_found" }, { status: 404 }); + return Response.json({ error: "not_found", message: "Request not found" }, { status: 404 }); } return Response.json(extracts ? (await withEmailExtracts([data]))[0] : data); diff --git a/apps/web/app/api/requests/[id]/shares/route.ts b/apps/web/app/api/requests/[id]/shares/route.ts index 68b6ba48e..ce6ac050b 100644 --- a/apps/web/app/api/requests/[id]/shares/route.ts +++ b/apps/web/app/api/requests/[id]/shares/route.ts @@ -12,12 +12,12 @@ import { isUuid } from "@/lib/uuid"; // approval, lib/approvals). Listing them takes any key of the account. const SHARE_ERRORS = { - not_found: { status: 404, message: "not_found" }, - email: { status: 400, message: "Emails cannot be shared" }, - not_owner: { status: 403, message: "Only the endpoint's owner can share its requests" }, + not_found: { status: 404, body: { error: "not_found", message: "Request not found" } }, + email: { status: 400, body: { error: "Emails cannot be shared" } }, + not_owner: { status: 403, body: { error: "Only the endpoint's owner can share its requests" } }, limit: { status: 409, - message: `You can have ${MAX_ACTIVE_SHARES} live share links. Revoke some first.`, + body: { error: `You can have ${MAX_ACTIVE_SHARES} live share links. Revoke some first.` }, }, } as const; @@ -62,7 +62,9 @@ export async function POST(request: Request, { params }: { params: Promise<{ id: } const hideSensitive = body.hideSensitive !== false; - if (!isUuid(id)) return Response.json({ error: "not_found" }, { status: 404 }); + if (!isUuid(id)) { + return Response.json({ error: "not_found", message: "Request not found" }, { status: 404 }); + } // An API key or agent token: the account's owner approves the link first. if (auth.keyId) { @@ -82,14 +84,14 @@ export async function POST(request: Request, { params }: { params: Promise<{ id: hideSensitive, }); if (!result.ok) { - const { status, message } = SHARE_ERRORS[result.error]; + const { status, body: answer } = SHARE_ERRORS[result.error]; await auditUserAction(request, auth.userId, { action: "request.share_created", status, targetId: id, reason: result.error, }); - return Response.json({ error: message }, { status }); + return Response.json(answer, { status }); } await auditUserAction(request, auth.userId, { diff --git a/apps/web/changelog/web/readable-not-found-errors.json b/apps/web/changelog/web/readable-not-found-errors.json new file mode 100644 index 000000000..76d769f13 --- /dev/null +++ b/apps/web/changelog/web/readable-not-found-errors.json @@ -0,0 +1,8 @@ +{ + "title": "Readable not-found errors", + "items": [ + "A not_found answer carries a readable message beside its code (\"Request not found\", \"Endpoint not found\", \"Attachment not found\", \"Share link not found\", \"Connected agent not found\", \"Google connection not found\") on the request, endpoint request list, attachment, share link, connected agent and Google connection routes", + "The hosted MCP server calls a refusal because something already exists or is in use (HTTP 409) a conflict rather than a validation error", + "The changelog lists SDK 1.31.1" + ] +} diff --git a/apps/web/lib/changelog.ts b/apps/web/lib/changelog.ts index 323b96e6a..bfd6718db 100644 --- a/apps/web/lib/changelog.ts +++ b/apps/web/lib/changelog.ts @@ -31,7 +31,7 @@ const RELEASE = release as { version: string | null; entries: ChangelogEntry[] } export const APP_VERSION: string = RELEASE.version ?? "dev"; export const CLI_VERSION = "1.20.1"; -export const SDK_VERSION = "1.31.0"; +export const SDK_VERSION = "1.31.1"; export const PYTHON_SDK_VERSION = "0.10.1"; export const GO_SDK_VERSION = "0.10.1"; export const MCP_VERSION = "2.5.0"; @@ -2546,6 +2546,15 @@ export const CHANGELOG: ChangelogEntry[] = [ }, // ─── SDK ──────────────────────────────────────────────────────────── + { + version: "1.31.1", + date: "2026-11-16", + title: "Readable Errors For Bare Codes", + track: "sdk", + items: [ + 'An error whose body names only a code (`{ "error": "not_found" }`) reads as the status in words, with its hint, instead of the code alone: "Not found" when the code only names the status, and the code in brackets when it says more ("Bad request (invalid_since)"); the code is still the error\'s `code`', + ], + }, { version: "1.31.0", date: "2026-11-16", @@ -3041,6 +3050,7 @@ export const CHANGELOG: ChangelogEntry[] = [ items: [ "An error's `message` is the API's text, not its JSON: the `message` of a JSON error body, else its `error`, so a long answer is no longer cut into broken JSON", "A duration string too long or too large for a float (400 digits, or a huge value with a unit) raises the invalid-duration `ValueError` instead of becoming an endless wait", + 'An error whose body names only a code (`{"error": "not_found"}`) reads as the status in words instead of the code alone: "Not found" when the code only names the status, and the code in brackets when it says more ("Bad request (invalid_since)"); `InvalidCursorError` and `RateLimitError.code` still read the code', ], }, { @@ -3192,6 +3202,7 @@ export const CHANGELOG: ChangelogEntry[] = [ track: "go", items: [ 'An `Error`\'s `Message` is the API\'s text, not its JSON: the `message` of a JSON error body, else its `error`, so a long answer is no longer cut into broken JSON; a short one gets its hint after ": " (404) or ". " (401), as in the other SDKs, and `errors.Is(err, ErrInvalidCursor)` reads the body\'s code as before', + 'An error whose body names only a code (`{"error":"not_found"}`) reads as the status in words instead of the code alone: "Not found" when the code only names the status, and the code in brackets when it says more ("Bad request (invalid_since)"); `errors.Is(err, ErrInvalidCursor)` still reads the code', ], }, { @@ -3326,6 +3337,8 @@ export const CHANGELOG: ChangelogEntry[] = [ "`describe` answers the SDK version and its sections' operation names (about 2.5 KB, from 33 KB); `section` returns one section's parameters and types", "The tool list is smaller: conditions of response rules, filters and layouts are described once per list, a rule's response once as `mockResponse`, and input schemas leave out the `$schema` URI (MCP reads JSON Schema 2020-12 without it). The core list is 59.1 KB as sent (from 63.4 KB), the full one 119.3 KB (from 128.1 KB)", "On the hosted server, names in `?tools=` that are no group are reported on `describe` and in the instructions, and when none of the names is a group the client's own default applies rather than the core", + 'An API error that names only a code reads as the status in words ("Not found" for a request id that does not exist, with the `list_requests` hint), keeping the code in brackets when it says more ("Bad request (invalid_since)")', + "A refusal because something already exists or is in use (HTTP 409) has the tool error code `conflict`, not `validation_error`", ], }, { diff --git a/content/docs/sdk/api.mdx b/content/docs/sdk/api.mdx index e3fac4f7f..ecc39b7b4 100644 --- a/content/docs/sdk/api.mdx +++ b/content/docs/sdk/api.mdx @@ -1997,6 +1997,6 @@ import { `WebhooksCCError.code` is the API's own error code when its answer had one, such as `"invalid_cursor"` or `"search_busy"` from `requests.searchPage()`. -`message` is what the API said as plain text (the `message` of a JSON error body, else its `error`), followed by the SDK's recovery hint when the text is short. `apiMessage` is the same text without the hint, and `path` is the API route that answered, after `/api` (such as `/endpoints/acme`); both are set on errors made from an API answer. +`message` is what the API said as plain text (the `message` of a JSON error body, else its `error`; when that is only a code (`not_found`), the status in words, with the code in brackets when it says more (`Bad request (invalid_since)`), and `code` still holds it when it came from `error`), followed by the SDK's recovery hint when the text is short. `apiMessage` is the same text without the hint, and `path` is the API route that answered, after `/api` (such as `/endpoints/acme`); both are set on errors made from an API answer. `WebhookVerificationError.code` is `"missing_headers"`, `"timestamp_out_of_range"`, `"invalid_signature"` or `"invalid_payload"`. Answer the first three with 401 and `invalid_payload` with 400. diff --git a/content/docs/sdk/go.mdx b/content/docs/sdk/go.mdx index 63cb73e35..918d35a4e 100644 --- a/content/docs/sdk/go.mdx +++ b/content/docs/sdk/go.mdx @@ -466,7 +466,7 @@ client, err := connection.Wait(ctx) ## Errors -API errors are a `*webhookscc.Error` with a `StatusCode` and a `Message`, the API's own text (the `message` of a JSON error body, else its `error`) with a recovery hint when it is short. Test them with `errors.Is`: +API errors are a `*webhookscc.Error` with a `StatusCode` and a `Message`, the API's own text (the `message` of a JSON error body, else its `error`; when that is only a code (`not_found`), the status in words, with the code in brackets when it says more (`Bad request (invalid_since)`)) with a recovery hint when it is short. Test them with `errors.Is`: | Error | When | | ----------------------------- | --------------------------------------------------------------- | diff --git a/content/docs/sdk/python.mdx b/content/docs/sdk/python.mdx index c591d6633..1c5b33988 100644 --- a/content/docs/sdk/python.mdx +++ b/content/docs/sdk/python.mdx @@ -377,7 +377,7 @@ client = pending.wait() ## Errors -API errors raise `WebhooksCCError` with a `status_code` and a `message`, the API's own text (the `message` of a JSON error body, else its `error`) with a recovery hint when it is short, or one of its subclasses: +API errors raise `WebhooksCCError` with a `status_code` and a `message`, the API's own text (the `message` of a JSON error body, else its `error`; when that is only a code (`not_found`), the status in words, with the code in brackets when it says more (`Bad request (invalid_since)`)) with a recovery hint when it is short, or one of its subclasses: | Error | When | | -------------------- | ------------------------------------------------------------- | diff --git a/packages/mcp/src/__tests__/tools.test.ts b/packages/mcp/src/__tests__/tools.test.ts index a1ab686a5..7fb79c0a1 100644 --- a/packages/mcp/src/__tests__/tools.test.ts +++ b/packages/mcp/src/__tests__/tools.test.ts @@ -4265,6 +4265,30 @@ describe("errors from the API", () => { expect(error.hint).toContain("list_endpoints"); }); + it("says the status in words when the API answers only a code", async () => { + const tools = getRegisteredTools(failingClient(404, '{"error":"not_found"}')); + const result = await tools.get_request.handler({ requestId: "req_missing" }); + expect(result.isError).toBe(true); + const error = parseJsonResult(result); + expect(error.code).toBe("not_found"); + expect(error.message).toBe("Not found"); + expect(error.hint).toContain("list_requests"); + // A code that says more than the status is kept. + const since = getRegisteredTools(failingClient(400, '{"error":"invalid_since"}')); + const refused = parseJsonResult( + await since.list_requests.handler({ endpointSlug: "acme", limit: 5 }) + ); + expect(refused.message).toBe("Bad request (invalid_since)"); + expect(refused.code).toBe("validation_error"); + }); + + it("calls a 409 a conflict", async () => { + const tools = getRegisteredTools(failingClient(409, '{"error":"slug_exists"}')); + const error = parseJsonResult(await tools.get_endpoint.handler({ slug: "acme" })); + expect(error.code).toBe("conflict"); + expect(error.message).toBe("Conflict (slug_exists)"); + }); + it("never answers raw JSON or the SDK's method names as an error", async () => { const bodies: Array<[number, string]> = [ [404, '{"error":"Endpoint not found"}'], diff --git a/packages/mcp/src/tools.ts b/packages/mcp/src/tools.ts index da3f37057..8d4c17d5a 100644 --- a/packages/mcp/src/tools.ts +++ b/packages/mcp/src/tools.ts @@ -1158,7 +1158,13 @@ function splitHint(message: string): { message: string; hint: string | null } { /** The codes a tool error carries. */ export type ToolErrorCode = - "unauthorized" | "not_found" | "rate_limited" | "timeout" | "validation_error" | "server_error"; + | "unauthorized" + | "not_found" + | "conflict" + | "rate_limited" + | "timeout" + | "validation_error" + | "server_error"; /** A tool error as every tool answers one. */ interface ToolErrorPayload { @@ -1264,7 +1270,12 @@ function errorPayload(error: unknown, remote: boolean): ToolErrorPayload { } else if (error instanceof TimeoutError) { payload.code = "timeout"; } else if (error instanceof WebhooksCCError) { - payload.code = error.statusCode >= 500 ? "server_error" : "validation_error"; + payload.code = + error.statusCode >= 500 + ? "server_error" + : error.statusCode === 409 + ? "conflict" + : "validation_error"; } if (error instanceof WebhooksCCError) { diff --git a/packages/sdk-go/client.go b/packages/sdk-go/client.go index b8e5dbcb1..7639d86d2 100644 --- a/packages/sdk-go/client.go +++ b/packages/sdk-go/client.go @@ -504,6 +504,43 @@ func notFoundHint(path string) string { // cannot make a huge message. const maxErrorText = 1000 +// bareCode is an error code rather than text: lower case, digits and underscores. +var bareCode = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) + +// statusText is a short plain sentence for an error status, for a body +// that names only a code. +func statusText(status int) string { + switch status { + case http.StatusBadRequest: + return "Bad request" + case http.StatusUnauthorized: + return "Unauthorized" + case http.StatusForbidden: + return "Forbidden" + case http.StatusNotFound: + return "Not found" + case http.StatusConflict: + return "Conflict" + case http.StatusTooManyRequests: + return "Too many requests" + } + if status >= 500 { + return "Server error" + } + return fmt.Sprintf("Request failed with HTTP %d", status) +} + +// codeText is the status in words for a body that names only code: alone +// when the code just names the status (not_found on a 404), else with the +// code in brackets, since it says what went wrong ("Bad request (invalid_since)"). +func codeText(status int, code string) string { + words := statusText(status) + if strings.ReplaceAll(code, "_", " ") == strings.ToLower(words) { + return words + } + return words + " (" + code + ")" +} + // errorText is the plain text of a JSON error body: its string "message", // else its string "error"; false when the body is not a JSON object naming // either. @@ -546,6 +583,9 @@ func errorFromResponse(response *apiResponse, path string) *Error { if utf8.RuneCountInString(message) > 200 { message = string([]rune(message)[:200]) + "..." } + } else if bareCode.MatchString(message) { + // A bare code ({"error": "not_found"}) is no sentence: say the status (see codeText). + message = codeText(response.status, message) } generic := len(message) < 30 apiErr := &Error{StatusCode: response.status, Message: message} diff --git a/packages/sdk-go/client_test.go b/packages/sdk-go/client_test.go index 746dde93c..a78003467 100644 --- a/packages/sdk-go/client_test.go +++ b/packages/sdk-go/client_test.go @@ -1262,12 +1262,25 @@ func TestErrorMessagesAreThePlainTextOfTheBody(t *testing.T) { {400, `{"error":"invalid_input","message":"name is too long"}`, "name is too long"}, {502, "Bad gateway", "Bad gateway"}, {401, `{"error":"Unauthorized"}`, "Unauthorized. Get an API key at https://webhooks.cc/account/api-keys"}, - {400, `{"error":"invalid_input","message":"` + strings.Repeat("y", 250) + `"}`, strings.Repeat("y", 250)}, + {400, `{"error":"invalid_input","message":"` + strings.Repeat("y ", 125) + `"}`, strings.Repeat("y ", 125)}, {500, strings.Repeat("z", 400), strings.Repeat("z", 200) + "..."}, // A message only JavaScript's trim() calls blank (U+FEFF) gives way to the error. {400, `{"message":"\ufeff ","error":"name is too long"}`, "name is too long"}, // A short message is trimmed as JavaScript trims it before its hint. {404, "\ufeffNot found\ufeff", "Not found: Use Endpoints.List to see your endpoints"}, + // A bare code is no sentence: the status is said in words instead. + {404, `{"error":"not_found"}`, "Not found: Use Endpoints.List to see your endpoints"}, + {404, `{"error":"Request not found"}`, "Request not found: Use Endpoints.List to see your endpoints"}, + {404, `{"error":"not_found","message":"Request not found"}`, "Request not found: Use Endpoints.List to see your endpoints"}, + {401, `{"error":"unauthorized"}`, "Unauthorized. Get an API key at https://webhooks.cc/account/api-keys"}, + {403, `{"error":"forbidden"}`, "Forbidden"}, + {409, `{"error":"conflict"}`, "Conflict"}, + // A code that says more than the status stays, in brackets. + {400, `{"error":"invalid_since"}`, "Bad request (invalid_since)"}, + {409, `{"error":"slug_exists"}`, "Conflict (slug_exists)"}, + {500, `{"error":"internal_error"}`, "Server error (internal_error)"}, + {410, `{"error":"expired"}`, "Request failed with HTTP 410 (expired)"}, + {410, `{"message":"expired"}`, "Request failed with HTTP 410 (expired)"}, } for _, c := range cases { api := newFakeAPI(t) diff --git a/packages/sdk-go/internal_test.go b/packages/sdk-go/internal_test.go index a746245c1..2cff50494 100644 --- a/packages/sdk-go/internal_test.go +++ b/packages/sdk-go/internal_test.go @@ -316,6 +316,22 @@ func TestSearchCollectsMoreThanAPageHolds(t *testing.T) { } } +// A bare code gives way to the status in words, and stays the error's code. +func TestABareCodeIsKeptAsTheCode(t *testing.T) { + cases := []struct { + body, message, code string + }{ + {`{"error":"not_found"}`, "Not found: Use Endpoints.List to see your endpoints", "not_found"}, + {`{"error":"not_found","message":"Request not found"}`, "Request not found: Use Endpoints.List to see your endpoints", "not_found"}, + } + for _, c := range cases { + err := errorFromResponse(&apiResponse{status: http.StatusNotFound, body: []byte(c.body)}, "/requests/r1") + if err.Message != c.message || err.code != c.code { + t.Errorf("%s: message %q, code %q", c.body, err.Message, err.code) + } + } +} + // An error on a later page is the call's error, never a short result. func TestAnErrorOnALaterPageIsReturned(t *testing.T) { ctx := context.Background() diff --git a/packages/sdk-python/src/webhooks_cc/client.py b/packages/sdk-python/src/webhooks_cc/client.py index fc103a2ce..72e090062 100644 --- a/packages/sdk-python/src/webhooks_cc/client.py +++ b/packages/sdk-python/src/webhooks_cc/client.py @@ -291,6 +291,34 @@ def _error_code(message: str) -> str | None: _MAX_ERROR_TEXT = 1_000 +# An error code rather than text: lower case, digits and underscores. +_BARE_CODE = re.compile(r"[a-z][a-z0-9_]*") + +_STATUS_TEXT = { + 400: "Bad request", + 401: "Unauthorized", + 403: "Forbidden", + 404: "Not found", + 409: "Conflict", + 429: "Too many requests", +} + + +def _status_text(status: int) -> str: + """A short plain sentence for an error status, for a body that names only a code.""" + if status in _STATUS_TEXT: + return _STATUS_TEXT[status] + return "Server error" if status >= 500 else f"Request failed with HTTP {status}" + + +def _code_text(status: int, code: str) -> str: + """The status in words for a body that names only ``code``: alone when the + code just names the status (``not_found`` on a 404), else with the code in + brackets, since it says what went wrong (``Bad request (invalid_since)``).""" + words = _status_text(status) + return words if code.replace("_", " ") == words.lower() else f"{words} ({code})" + + def _error_text(body: str) -> str | None: """The plain text of a JSON error body: its string ``message``, else its string ``error``; None when the body is not a JSON object naming either.""" @@ -317,6 +345,9 @@ def _error_from_response(response: httpx.Response) -> WebhooksCCError: plain = _error_text(text) if plain is None: plain = text[:200] + "..." if len(text) > 200 else text + elif _BARE_CODE.fullmatch(plain): + # A bare code ({"error": "not_found"}) is no sentence: say the status (see _code_text). + plain = _code_text(response.status_code, plain) return _map_error(response.status_code, plain, response.headers, path, text) diff --git a/packages/sdk-python/tests/test_client.py b/packages/sdk-python/tests/test_client.py index 6f1912391..d5bc16b1d 100644 --- a/packages/sdk-python/tests/test_client.py +++ b/packages/sdk-python/tests/test_client.py @@ -865,10 +865,39 @@ def test_errors_are_typed(status: int, error_type: type[Exception]) -> None: "name is too long", ), (502, "Bad gateway", "Bad gateway"), - (400, json.dumps({"error": "invalid_input", "message": "y" * 250}), "y" * 250), + (400, json.dumps({"error": "invalid_input", "message": "y " * 125}), "y " * 125), (500, "z" * 400, "z" * 200 + "..."), # A message only JavaScript's trim() calls blank (U+FEFF) gives way to the error. (400, '{"message":"\\ufeff ","error":"name is too long"}', "name is too long"), + # A bare code is no sentence: the status is said in words instead. + ( + 404, + '{"error":"not_found"}', + "Not found: use client.endpoints.list() to see your endpoints", + ), + ( + 404, + '{"error":"Request not found"}', + "Request not found: use client.endpoints.list() to see your endpoints", + ), + ( + 404, + '{"error":"not_found","message":"Request not found"}', + "Request not found: use client.endpoints.list() to see your endpoints", + ), + ( + 401, + '{"error":"unauthorized"}', + "Unauthorized. Get an API key at https://webhooks.cc/account/api-keys", + ), + (403, '{"error":"forbidden"}', "Forbidden"), + (409, '{"error":"conflict"}', "Conflict"), + # A code that says more than the status stays, in brackets. + (400, '{"error":"invalid_since"}', "Bad request (invalid_since)"), + (409, '{"error":"slug_exists"}', "Conflict (slug_exists)"), + (500, '{"error":"internal_error"}', "Server error (internal_error)"), + (410, '{"error":"expired"}', "Request failed with HTTP 410 (expired)"), + (410, '{"message":"expired"}', "Request failed with HTTP 410 (expired)"), ], ) def test_error_messages_are_the_plain_text_of_the_body( @@ -881,6 +910,20 @@ def test_error_messages_are_the_plain_text_of_the_body( assert not caught.value.message.startswith("{") +def test_a_bare_code_keeps_its_meaning() -> None: + cursor = make_client(lambda request: httpx.Response(400, json={"error": "invalid_cursor"})) + with pytest.raises(errors.InvalidCursorError): + cursor.endpoints.get("acme") + busy = make_client(lambda request: httpx.Response(429, json={"error": "search_busy"})) + with pytest.raises(errors.RateLimitError) as caught: + busy.endpoints.get("acme") + assert caught.value.code == "search_busy" + plain = make_client(lambda request: httpx.Response(400, json={"error": "invalid_input"})) + with pytest.raises(errors.WebhooksCCError) as other: + plain.endpoints.get("acme") + assert other.value.message == "Bad request (invalid_input)" + + def test_rate_limit_error_carries_the_headers() -> None: headers = { "retry-after": "7", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index bd9e86aaf..4b3a95b03 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@webhooks-cc/sdk", - "version": "1.31.0", + "version": "1.31.1", "description": "TypeScript SDK for webhooks.cc \u2014 create endpoints, capture requests, assert in tests", "main": "dist/index.js", "module": "dist/index.mjs", diff --git a/packages/sdk/src/__tests__/checkouts.test.ts b/packages/sdk/src/__tests__/checkouts.test.ts index 4830bbd71..216a10a3b 100644 --- a/packages/sdk/src/__tests__/checkouts.test.ts +++ b/packages/sdk/src/__tests__/checkouts.test.ts @@ -205,11 +205,11 @@ describe("billing checkout links", () => { retry: { maxAttempts: 1 }, }); // A failure that keeps coming back ends the wait with that failure. - const busy = vi.fn().mockResolvedValue(answer({ error: "busy" }, 503)); + const busy = vi.fn().mockResolvedValue(answer({ error: "Server busy" }, 503)); globalThis.fetch = busy; const failed = once.billing.waitForCheckout(ID, { pollInterval: 1_000 }).catch((e) => e); await vi.advanceTimersByTimeAsync(20_000); - expect(((await failed) as Error).message).toContain("busy"); + expect(((await failed) as Error).message).toContain("Server busy"); expect(busy).toHaveBeenCalledTimes(10); // An answer in between starts the count again. diff --git a/packages/sdk/src/__tests__/client.test.ts b/packages/sdk/src/__tests__/client.test.ts index 25fa36db9..42bbee115 100644 --- a/packages/sdk/src/__tests__/client.test.ts +++ b/packages/sdk/src/__tests__/client.test.ts @@ -2670,6 +2670,43 @@ describe("WebhooksCC", () => { expect(error.code).toBe("invalid_cursor"); }); + it("says the status in words when the body names only a code", async () => { + const error = await failWith(404, '{"error":"not_found"}'); + expect(error).toBeInstanceOf(NotFoundError); + expect(error.apiMessage).toBe("Not found"); + expect(error.message).toBe( + "Not found: Use client.endpoints.list() to see available endpoints." + ); + expect(error.code).toBe("not_found"); + for (const [status, code, text] of [ + [401, "unauthorized", "Unauthorized"], + [403, "forbidden", "Forbidden"], + [409, "conflict", "Conflict"], + [429, "too_many_requests", "Too many requests"], + [400, "invalid_since", "Bad request (invalid_since)"], + [409, "slug_exists", "Conflict (slug_exists)"], + [500, "internal_error", "Server error (internal_error)"], + [503, "unavailable", "Server error (unavailable)"], + [410, "expired", "Request failed with HTTP 410 (expired)"], + ] as const) { + const coded = await failWith(status, JSON.stringify({ error: code })); + expect(coded.apiMessage, String(status)).toBe(text); + expect(coded.code, String(status)).toBe(code); + } + // A message that is only a code keeps it too. + const message = await failWith(410, '{"message":"expired"}'); + expect(message.apiMessage).toBe("Request failed with HTTP 410 (expired)"); + }); + + it("keeps an error that is a sentence, and a message beside a code", async () => { + const sentence = await failWith(404, '{"error":"Request not found"}'); + expect(sentence.apiMessage).toBe("Request not found"); + expect(sentence.code).toBeUndefined(); + const both = await failWith(404, '{"error":"not_found","message":"Request not found"}'); + expect(both.apiMessage).toBe("Request not found"); + expect(both.code).toBe("not_found"); + }); + it("lets a message only trim() calls blank (U+FEFF) give way to the error", async () => { const error = await failWith(400, '{"message":"\\ufeff ","error":"name is too long"}'); expect(error.apiMessage).toBe("name is too long"); @@ -2682,7 +2719,7 @@ describe("WebhooksCC", () => { }); it("reads the whole JSON body even when it is over 200 characters", async () => { - const long = "y".repeat(250); + const long = "y ".repeat(125); const error = await failWith(400, JSON.stringify({ error: "invalid_input", message: long })); expect(error.message).toBe(long); expect(error.message.startsWith("{")).toBe(false); diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts index 610c2805b..8ae27b886 100644 --- a/packages/sdk/src/client.ts +++ b/packages/sdk/src/client.ts @@ -282,7 +282,9 @@ function mapStatusToError( /** The whole body, when `message` was cut short, to find its code in. */ body?: string ): WebhooksCCError { - const plain = errorTextOf(body ?? message) ?? message; + const text = errorTextOf(body ?? message); + // A bare code (`{ "error": "not_found" }`) is no sentence: say the status (see codeText). + const plain = text === undefined ? message : BARE_CODE.test(text) ? codeText(status, text) : text; const error = statusError(status, plain, response, path); error.apiMessage = plain; if (path !== undefined) error.path = path; @@ -291,6 +293,39 @@ function mapStatusToError( return error; } +/** An error code rather than text: lower case, digits and underscores. */ +const BARE_CODE = /^[a-z][a-z0-9_]*$/; + +/** A short plain sentence for an error status, for a body that names only a code. */ +function statusText(status: number): string { + switch (status) { + case 400: + return "Bad request"; + case 401: + return "Unauthorized"; + case 403: + return "Forbidden"; + case 404: + return "Not found"; + case 409: + return "Conflict"; + case 429: + return "Too many requests"; + default: + return status >= 500 ? "Server error" : `Request failed with HTTP ${status}`; + } +} + +/** + * The status in words for a body that names only `code`: alone when the + * code just names the status (`not_found` on a 404), else with the code in + * brackets, since it says what went wrong (`Bad request (invalid_since)`). + */ +function codeText(status: number, code: string): string { + const words = statusText(status); + return code.replace(/_/g, " ") === words.toLowerCase() ? words : `${words} (${code})`; +} + /** Longest text taken from a JSON error body, so one answer cannot make a huge message. */ const MAX_ERROR_TEXT = 1_000; @@ -342,7 +377,7 @@ function errorCodeOf(body: string): string | undefined { try { const parsed = JSON.parse(body) as { code?: unknown } | null; const code = parsed && typeof parsed === "object" ? parsed.code : undefined; - return typeof code === "string" && /^[a-z][a-z0-9_]*$/.test(code) ? code : undefined; + return typeof code === "string" && BARE_CODE.test(code) ? code : undefined; } catch { return undefined; }