From 71e2f18e19fae212af42400c1f2c477a289e0acc Mon Sep 17 00:00:00 2001 From: davelopez <46503462+davelopez@users.noreply.github.com> Date: Fri, 12 Jul 2024 14:10:49 +0200 Subject: [PATCH] Add middleware for error handling in Toolshed API client --- .../webapp/frontend/src/schema/fetcher.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/tool_shed/webapp/frontend/src/schema/fetcher.ts b/lib/tool_shed/webapp/frontend/src/schema/fetcher.ts index 7370e0ec351d..d8c0d22e6a70 100644 --- a/lib/tool_shed/webapp/frontend/src/schema/fetcher.ts +++ b/lib/tool_shed/webapp/frontend/src/schema/fetcher.ts @@ -1,5 +1,20 @@ -import createClient from "openapi-fetch" +import createClient, { Middleware } from "openapi-fetch" import type { paths as ToolShedApiPaths } from "./schema" +const errorHandlingMiddleware: Middleware = { + async onResponse({ response }) { + if (!response.ok) { + const errorMessage = response.headers.get("content-type")?.includes("json") + ? await response.clone().json() + : await response.clone().text() + throw new Error(`Request failed with status ${response.status}`, { + cause: errorMessage, + }) + } + }, +} + const client = createClient({ baseUrl: "" }) +client.use(errorHandlingMiddleware) + export { type ToolShedApiPaths, client }