Add type guards for errors (#746)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Hichem · committed by GitHub · parent ac3e614 · Browse files · 5 files·+91 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+91 added−8 removed
- tests:+4 added−2 removed
- other:+87 added−6 removed
Provenance
- Commit
7e1fd0b- Tree
055476c- Author
Hichem <fantar.hichem@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
ac3e614
5 files changed+91 added−8 removed
modified:source/core/Ky.ts+3 added-3 removed
1 import {HTTPError} from '../errors/HTTPError.js';2-import {TimeoutError} from '../errors/TimeoutError.js';2 import type {3 Input,4 InternalOptions,5 NormalizedOptions,7 unmodified lines13 import timeout, {type TimeoutOptions} from '../utils/timeout.js';14 import delay from '../utils/delay.js';15 import {type ObjectEntries} from '../utils/types.js';16 import {findUnknownOptions, hasSearchParameters} from '../utils/options.js';17+import {isHTTPError, isTimeoutError} from '../utils/type-guards.js';18 import {19 maxSafeTimeout,20 responseTypes,21 stop,236 unmodified lines258 259 protected _calculateRetryDelay(error: unknown) {260 this._retryCount++;261 262- if (this._retryCount > this._options.retry.limit || error instanceof TimeoutError) {262+ if (this._retryCount > this._options.retry.limit || isTimeoutError(error)) {263 throw error;264 }265 266- if (error instanceof HTTPError) {266+ if (isHTTPError(error)) {267 if (!this._options.retry.statusCodes.includes(error.response.status)) {268 throw error;269 }270 92 unmodified linesadded:source/utils/type-guards.ts+72 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import {HTTPError} from '../errors/HTTPError.js';import {TimeoutError} from '../errors/TimeoutError.js';
/** * Type guard to check if an error is a Ky error (HTTPError or TimeoutError). * * @param error - The error to check * @returns `true` if the error is a Ky error, `false` otherwise * * @example * ``` * import ky, {isKyError} from 'ky'; * try { * const response = await ky.get('/api/data'); * } catch (error) { * if (isKyError(error)) { * // Handle Ky-specific errors * console.log('Ky error occurred:', error.message); * } else { * // Handle other errors * console.log('Unknown error:', error); * } * } * ``` */export function isKyError(error: unknown): error is HTTPError | TimeoutError { return isHTTPError(error) || isTimeoutError(error);}
/** * Type guard to check if an error is an HTTPError. * * @param error - The error to check * @returns `true` if the error is an HTTPError, `false` otherwise * * @example * ``` * import ky, {isHTTPError} from 'ky'; * try { * const response = await ky.get('/api/data'); * } catch (error) { * if (isHTTPError(error)) { * console.log('HTTP error status:', error.response.status); * } * } * ``` */export function isHTTPError<T = unknown>(error: unknown): error is HTTPError<T> { return error instanceof HTTPError || ((error as any)?.name === HTTPError.name);}
/** * Type guard to check if an error is a TimeoutError. * * @param error - The error to check * @returns `true` if the error is a TimeoutError, `false` otherwise * * @example * ``` * import ky, {isTimeoutError} from 'ky'; * try { * const response = await ky.get('/api/data', { timeout: 1000 }); * } catch (error) { * if (isTimeoutError(error)) { * console.log('Request timed out:', error.request.url); * } * } * ``` */export function isTimeoutError(error: unknown): error is TimeoutError { return error instanceof TimeoutError || ((error as any)?.name === TimeoutError.name);}modified:source/index.ts+1 added
57 unmodified lines585960616257 unmodified linesexport type {KyRequest} from './types/request.js';export type {KyResponse} from './types/response.js';export {HTTPError} from './errors/HTTPError.js';export {TimeoutError} from './errors/TimeoutError.js';export {isKyError, isHTTPError, isTimeoutError} from './utils/type-guards.js';modified:test/hooks.ts+4 added-2 removed
1 import test from 'ava';2 import delay from 'delay';3-import ky, {HTTPError} from '../source/index.js';3+import ky, {HTTPError, isHTTPError} from '../source/index.js';4 import {type Options} from '../source/types/options.js';5 import {createHttpTestServer} from './helpers/create-http-test-server.js';6 7 test('hooks can be async', async t => {396 unmodified lines404 hooks: {405 beforeRetry: [406 ({error, retryCount}) => {407 t.true(error instanceof HTTPError);408+ t.true(isHTTPError(error));409 t.true(retryCount >= 1);410 },411 ],412 },44 unmodified lines457 await server.close();458 });459 460 test('beforeRetry hook with parseJson and error.response.json()', async t => {460- t.plan(10);461+ t.plan(11);462 463 let requestCount = 0;464 465 const server = await createHttpTestServer();16 unmodified lines482 hooks: {483 beforeRetry: [484 async ({error, retryCount}) => {485 t.true(error instanceof HTTPError);486+ t.true(isHTTPError(error));487 t.is(error.message, `Request failed with status code 502 Bad Gateway: GET ${server.url}/`);488 t.true((error as HTTPError).response instanceof Response);489 t.deepEqual(await (error as HTTPError).response.json(), {awesome: true});490 t.is(retryCount, 1);186 unmodified linesmodified:readme.md+11 added-3 removed
620 unmodified lines621 622 If you need to read the actual response when an `HTTPError` has occurred, call the respective parser method on the response object. For example:623 624 ```js625-import { HTTPError } from "ky";625+import {isKyError, isHTTPError, isTimeoutError} from 'ky';626 627 try {628 await ky('https://example.com').json();629 } catch (error) {630- if (error instanceof HTTPError) {631- const errorJson = await error.response.json();630+ if (isKyError(error)) {631+ if (isHTTPError(error)) {632+ console.log('Status:', error.response.status);633+ const errorJson = await error.response.json();634+ } else if (isTimeoutError(error)) {635+ console.log('Timeout URL:', error.request.url);636+ }637+ } else {638+ // Handle other errors639+ console.log('Unknown error:', error);640 }641 }642 ```643 148 unmodified lines