Skip to content

Commit

Permalink
refactor: use try/catch instead of promise chainning
Browse files Browse the repository at this point in the history
  • Loading branch information
alfetopito committed Jan 10, 2025
1 parent 5109f10 commit 40a994f
Showing 1 changed file with 25 additions and 25 deletions.
50 changes: 25 additions & 25 deletions apps/cowswap-frontend/src/modules/usdAmount/apis/getBffUsdPrice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,31 +30,31 @@ const fetchRateLimited = fetchWithRateLimit({
export async function getBffUsdPrice(currency: Token): Promise<Fraction | null> {
const url = `${BFF_BASE_URL}/${currency.chainId}/tokens/${currency.address}/usdPrice`

return fetchRateLimited(url)
.then((res) => res.json())
.catch((error) => {
if (error.message === 'Price not found') {
// TODO: will a 404 response be caught here?
throw new UnknownCurrencyError({
cause: `BFF did not return a price for '${currency.address}' on chain '${currency.chainId}'`,
})
}

return Promise.reject(error)
})
.then((res: BffResponse) => {
if (isErrorResponse(res)) {
if (res.message === 'Price not found') {
throw new UnknownCurrencyError({
cause: `BFF did not return a price for '${currency.address}' on chain '${currency.chainId}'`,
})
}

throw new Error(`Unexpected response from BFF: ${JSON.stringify(res)}`)
}

return FractionUtils.fromNumber(res.price)
})
try {
const res = await fetchRateLimited(url)

// Token not found
if (res.status === 404) {
throw new UnknownCurrencyError({
cause: `BFF did not return a price for '${currency.address}' on chain '${currency.chainId}'`,
})
// Unknown error case
} else if (res.status !== 200) {
throw new Error(`Unexpected response from BFF: ${res.status}`)
}

const data: BffResponse = await res.json()

// 200 response with error message
if (isErrorResponse(data)) {
throw new Error(`Unexpected response from BFF: ${JSON.stringify(data)}`)
}

// Happy path
return FractionUtils.fromNumber(data.price)
} catch (error) {
return Promise.reject(error)
}
}

function isErrorResponse(response: BffResponse): response is BffUsdErrorResponse {
Expand Down

0 comments on commit 40a994f

Please sign in to comment.