-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add middleware for error handling in Toolshed API client
- Loading branch information
Showing
1 changed file
with
16 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<ToolShedApiPaths>({ baseUrl: "" }) | ||
client.use(errorHandlingMiddleware) | ||
|
||
export { type ToolShedApiPaths, client } |