Skip to content

Commit

Permalink
chore(open-payments): parse error objects, and return error codes
Browse files Browse the repository at this point in the history
  • Loading branch information
mkurapov committed Jul 3, 2024
1 parent 5851525 commit 405a3c4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
1 change: 1 addition & 0 deletions packages/open-payments/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ try {
} catch (error) {
if (error instanceof OpenPaymentsClientError) {
console.log(error.message)
console.log(error.code) // the error code from the Open Payments API
console.log(error.description) // additional description of the error
console.log(error.status) // the HTTP status of the request, if a request failure
console.log(error.validationErrors) // an array of validation errors. Populated if the response of the request failed OpenAPI specfication validation, or other validation checks.
Expand Down
32 changes: 24 additions & 8 deletions packages/open-payments/src/client/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,23 +158,32 @@ const handleError = async (
let errorDescription
let errorStatus
let validationErrors
let errorCode

const { HTTPError } = await import('ky')

if (error instanceof HTTPError) {
let responseBody
let responseBody:
| {
error: { description: string; code: string }
}
| string
| undefined

try {
responseBody = (await error.response.json()) as { message: string }
responseBody = await error.response.text()
responseBody = JSON.parse(responseBody)
} catch {
// Ignore if we can't parse the response body (or no body exists)
}

errorStatus = error.response.status
errorDescription =
responseBody && responseBody.message
? responseBody.message
: error.message
errorStatus = error.response?.status
typeof responseBody === 'object'
? responseBody.error.description
: responseBody || error.message
errorCode =
typeof responseBody === 'object' ? responseBody.error.code : undefined
} else if (isValidationError(error)) {
errorDescription = 'Could not validate OpenAPI response'
validationErrors = error.errors.map((e) => e.message)
Expand All @@ -188,14 +197,21 @@ const handleError = async (

const errorMessage = `Error making Open Payments ${requestType} request`
deps.logger.error(
{ status: errorStatus, errorDescription, url, requestType },
{
method: requestType,
url,
status: errorStatus,
description: errorDescription,
code: errorCode
},
errorMessage
)

throw new OpenPaymentsClientError(errorMessage, {
description: errorDescription,
validationErrors,
status: errorStatus
status: errorStatus,
code: errorCode
})
}

Expand Down

0 comments on commit 405a3c4

Please sign in to comment.