Skip to content

Commit

Permalink
Export createHttpError()
Browse files Browse the repository at this point in the history
  • Loading branch information
tkrotoff committed Aug 1, 2019
1 parent 8a13801 commit a534716
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
7 changes: 7 additions & 0 deletions src/Http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -405,3 +405,10 @@ describe('checkStatus()', () => {
}
});
});

test('createHttpError()', () => {
const error = Http.createHttpError('Bad Request', HttpStatus._400_BadRequest, { error: 400 });
expect(error).toEqual(new HttpError('Bad Request'));
expect(error.status).toEqual(HttpStatus._400_BadRequest);
expect(error.response).toEqual({ error: 400 });
});
17 changes: 13 additions & 4 deletions src/Http.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { HttpError } from './HttpError';
import { HttpStatus } from './HttpStatus';

const JSON_MIME_TYPE = 'application/json';

Expand All @@ -16,6 +17,17 @@ export async function parseResponseBody(response: Response) {
return response.text();
}

export function createHttpError(
statusText: string,
status: HttpStatus,
parsedResponseBody: unknown
) {
const error = new HttpError(statusText);
error.status = status;
error.response = parsedResponseBody;
return error;
}

// See [Handling HTTP error statuses](https://github.com/github/fetch/blob/v3.0.0/README.md#handling-http-error-statuses)
// Exported for testing purpose only
export function checkStatus(response: Response, parsedResponseBody: unknown) {
Expand Down Expand Up @@ -46,10 +58,7 @@ export function checkStatus(response: Response, parsedResponseBody: unknown) {
// }

if (!response.ok) {
const error = new HttpError(response.statusText);
error.status = response.status;
error.response = parsedResponseBody;
throw error;
throw createHttpError(response.statusText, response.status, parsedResponseBody);
}
}

Expand Down

0 comments on commit a534716

Please sign in to comment.