Skip to content

Commit

Permalink
feat: add request to fetch error and test spec
Browse files Browse the repository at this point in the history
  • Loading branch information
pviti committed Nov 4, 2024
1 parent 090721c commit 10f44e6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
21 changes: 20 additions & 1 deletion specs/error.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

import { CommerceLayerClient } from '../src'
import { CommerceLayerClient, ErrorObj } from '../src'
import { ErrorType } from '../src/error'
import { getClient } from '../test/common'

Expand Down Expand Up @@ -40,4 +40,23 @@ describe('SDK:error suite', () => {
}
})


it('ErrorInterceptor.error', async () => {

cl = await getClient({})

cl.addResponseInterceptor(undefined, (error: ErrorObj): ErrorObj => {
expect(error).toBeDefined()
expect(error.request).toBeDefined()
return error
})

try {
await cl.customers.create({ email: '' })
} catch (error) {
expect(error.type).toBe(ErrorType.RESPONSE)
}

})

})
8 changes: 6 additions & 2 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@ export class FetchError extends Error {
readonly #errors?: any[]
readonly #status: number
readonly #statusText: string
readonly #request?: Partial<FetchRequestOptions>

constructor(status: number, statusText: string, body?: any) {
constructor(status: number, statusText: string, body?: any, request?: FetchRequestOptions) {
super(statusText)
this.#status = status
this.#statusText = statusText
if (body) this.#errors = body.errors
if (request) this.#request = request
}


Expand All @@ -41,6 +43,8 @@ export class FetchError extends Error {

get statusText(): string { return this.#statusText }

get request(): Partial<FetchRequestOptions> | undefined { return this.#request }

}


Expand Down Expand Up @@ -75,7 +79,7 @@ export const fetchURL = async (url: URL, requestOptions: FetchRequestOptions, cl
: undefined

if (!response.ok) {
let error = new FetchError(response.status, response.statusText, responseBody)
let error = new FetchError(response.status, response.statusText, responseBody, requestOptions)
if (interceptors?.response?.onFailure) error = await interceptors.response.onFailure(error)
if (error) throw error
}
Expand Down

0 comments on commit 10f44e6

Please sign in to comment.