Skip to content

Commit

Permalink
feat: use normalized HTTPError
Browse files Browse the repository at this point in the history
  • Loading branch information
angeloashmore committed May 11, 2021
1 parent 15d0187 commit 0eb9fab
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 4 deletions.
20 changes: 20 additions & 0 deletions src/HTTPError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export class HTTPError extends Error {
url: string
options: RequestInit
response: Response

constructor(
reason: string | undefined,
response: Response,
url: string,
options: RequestInit,
) {
super(
reason || `Network request failed with status code ${response.status}`,
)

this.url = url
this.options = options
this.response = response
}
}
7 changes: 3 additions & 4 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { getCookie } from './lib/getCookie'

import { Document, LinkResolver, Query, Ref, Repository } from './types'
import { buildQueryURL, BuildQueryURLArgs } from './buildQueryURL'
import { HTTPError } from './HTTPError'
import * as cookie from './cookie'
import * as predicate from './predicate'

Expand Down Expand Up @@ -845,11 +846,9 @@ export class Client {
// Content Type.
return await res.json()
} else if (res.status === 401) {
throw new Error(
'401 Unauthorized: A valid access token is required to access this repository.',
)
throw new HTTPError('Invalid access token', res, url, options)
} else {
throw new Error(`${res.status}: An unknown network error occured.`)
throw new HTTPError(undefined, res, url, options)
}
}
}
23 changes: 23 additions & 0 deletions test/client-get.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import test from 'ava'
import { Response } from 'node-fetch'
import * as mswNode from 'msw/node'

import { createMockQueryHandler } from './__testutils__/createMockQueryHandler'
Expand Down Expand Up @@ -103,3 +104,25 @@ test('merges params and default params if provided', async (t) => {

t.deepEqual(res, queryResponse)
})

test('throws if access token is invalid', async (t) => {
const queryResponse = createQueryResponse()

server.use(
createMockRepositoryHandler(t),
createMockQueryHandler(t, [queryResponse], 'accessToken', {
ref: 'masterRef',
}),
)

const client = createTestClient(t)

try {
await client.get()
} catch (error) {
t.true(/invalid access token/i.test(error.message))
t.is(error.url, `${client.endpoint}/documents/search?ref=masterRef`)
t.deepEqual(error.options, {})
t.true(error.response instanceof Response)
}
})

0 comments on commit 0eb9fab

Please sign in to comment.