From 0eb9fabe98b46db73fc31847213935a787b23a85 Mon Sep 17 00:00:00 2001 From: Angelo Ashmore Date: Mon, 10 May 2021 14:56:46 -1000 Subject: [PATCH] feat: use normalized HTTPError --- src/HTTPError.ts | 20 ++++++++++++++++++++ src/client.ts | 7 +++---- test/client-get.test.ts | 23 +++++++++++++++++++++++ 3 files changed, 46 insertions(+), 4 deletions(-) create mode 100644 src/HTTPError.ts diff --git a/src/HTTPError.ts b/src/HTTPError.ts new file mode 100644 index 00000000..0fafcfd5 --- /dev/null +++ b/src/HTTPError.ts @@ -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 + } +} diff --git a/src/client.ts b/src/client.ts index ea088150..bf040437 100644 --- a/src/client.ts +++ b/src/client.ts @@ -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' @@ -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) } } } diff --git a/test/client-get.test.ts b/test/client-get.test.ts index 515db8ef..00c3dfb2 100644 --- a/test/client-get.test.ts +++ b/test/client-get.test.ts @@ -1,4 +1,5 @@ import test from 'ava' +import { Response } from 'node-fetch' import * as mswNode from 'msw/node' import { createMockQueryHandler } from './__testutils__/createMockQueryHandler' @@ -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) + } +})