Skip to content

Commit

Permalink
extract handleApiError
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinxh committed Mar 18, 2024
1 parent 789541a commit 1298134
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
16 changes: 5 additions & 11 deletions packages/commerce-sdk-react/src/hooks/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
NullableParameters,
OmitNullableParameters
} from './types'
import {hasAllKeys} from './utils'
import {hasAllKeys, handleApiError} from './utils'
import {onClient} from '../utils'

/**
Expand Down Expand Up @@ -48,16 +48,10 @@ export const useQuery = <Client extends ApiClient, Options extends ApiOptions, D
// missing parameters. This will result in a runtime error. I think that this is an acceptable
// trade-off, as the behavior is opt-in by the end user, and it feels like adding type safety
// for this case would add significantly more complexity.
const wrappedMethod = async () => {
try {
return await authenticatedMethod(apiOptions as Options)
} catch (e) {
if (typeof e === 'object' && e !== null && 'response' in e) {
const json = await (e.response as Response).json()
throw json
}
throw e
}
const wrappedMethod = () => {
return handleApiError(() => {
return authenticatedMethod(apiOptions as Options)
})
}
return useReactQuery(hookConfig.queryKey, wrappedMethod, {
enabled:
Expand Down
12 changes: 12 additions & 0 deletions packages/commerce-sdk-react/src/hooks/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,15 @@ export const getCustomKeys = <T extends object>(obj: T) => {
}
return Object.keys(obj).filter((key: string): key is `c_${string}` => key.startsWith('c_'))
}

export const handleApiError = async <T>(func: () => Promise<T>): Promise<T> => {
try {
return await func()
} catch (e) {
if (typeof e === 'object' && e !== null && 'response' in e) {
const json = await (e.response as Response).json()
throw json
}
throw e
}
}

0 comments on commit 1298134

Please sign in to comment.