Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

fix(client): keep the API error code on ClientError (#1477)

skaffff3e39f5ce1a6e
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index 4517b2ab8..b478098c0 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -19,11 +19,18 @@ export type InferClientOutput<T> = T extends (...args: any[]) => Promise<infer O
export class ClientError extends Error {
status: number | undefined;
statusText: string | undefined;
-
- constructor(message: string, statusText?: string, status?: number) {
+ /**
+ * The API's machine-readable error code (`MedusaError.code`), when the
+ * error body carried one — e.g. `"insufficient_inventory"`. Lets a caller
+ * branch on the reason for a refusal without matching on `message`.
+ */
+ code: string | undefined;
+
+ constructor(message: string, statusText?: string, status?: number, code?: string) {
super(message);
this.statusText = statusText;
this.status = status;
+ this.code = code;
}
}
@@ -135,11 +142,13 @@ export function createClient(options: ClientOptions) {
if (response.status >= 300) {
const jsonError = (await response.json().catch(() => ({}))) as {
message?: string;
+ code?: string;
};
throw new ClientError(
jsonError.message ?? response.statusText,
response.statusText,
- response.status
+ response.status,
+ typeof jsonError.code === "string" ? jsonError.code : undefined
);
}