Add `beforeError` hook (#417)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Malolan B · committed by GitHub · parent 3e72832 · Browse files · 6 files·+134 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
Diff stats
6 files+134 added−2 removed
- tests:+66 added−1 removed
- other:+68 added−1 removed
Provenance
- Commit
616d276- Tree
d772aa5- Author
Malolan B <uchihamalolan@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
3e72832
6 files changed+134 added−2 removed
modified:source/core/Ky.ts+9 added-1 removed
37 unmodified lines38 39 ky._decorateResponse(response);40 41 if (!response.ok && ky._options.throwHttpErrors) {42- throw new HTTPError(response, ky.request, (ky._options as unknown) as NormalizedOptions);42+ let error = new HTTPError(response, ky.request, (ky._options as unknown) as NormalizedOptions);43+44+ for (const hook of ky._options.hooks.beforeError) {45+ // eslint-disable-next-line no-await-in-loop46+ error = await hook(error);47+ }48+49+ throw error;50 }51 52 // If `onDownloadProgress` is passed, it uses the stream API internally53 /* istanbul ignore next */56 unmodified lines110 hooks: deepMerge<Required<Hooks>>(111 {112 beforeRequest: [],113 beforeRetry: [],114+ beforeError: [],115 afterResponse: [],116 },117 options.hooks,118 ),200 unmodified linesmodified:source/types/hooks.ts+31 added
12345613 unmodified lines2021222324252627282967 unmodified lines979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129import {stop} from '../core/constants.js';import {HTTPError} from '../index.js';import type {NormalizedOptions} from './options.js';
export type BeforeRequestHook = ( request: Request,13 unmodified lines options: NormalizedOptions, response: Response) => Response | void | Promise<Response | void>;
export type BeforeErrorHook = (error: HTTPError) => HTTPError | Promise<HTTPError>;
export interface Hooks { /** This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives normalized input and options as arguments. You could, forf example, modiy `options.headers` here.
67 unmodified lines }); ``` */ afterResponse?: AfterResponseHook[];
/** This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a `HTTPError` as an argument and should return an instance of `HTTPError`.
@default []
@example ``` import ky from 'ky';
await ky('https://example.com', { hooks: { beforeError: [ error => { const {response} = error; if (response && response.body) { error.name = 'GitHubError'; error.message = `${response.body.message} (${response.statusCode})`; }
return error; } ] } }); ``` */ beforeError?: BeforeErrorHook[];}modified:source/index.ts+1 added
37 unmodified lines3839404142434445462 unmodified lines37 unmodified linesexport { Hooks, BeforeRequestHook, BeforeRetryHook, BeforeErrorHook, AfterResponseHook,} from './types/hooks.js';
export {ResponsePromise} from './types/response.js';2 unmodified linesmodified:test/helpers/with-page.ts-1 removed
12234514 unmodified linesimport process from 'node:process';// eslint-disable-next-line ava/use-testimport type {ExecutionContext, UntitledMacro} from 'ava';import {chromium, Page} from 'playwright-chromium';
type Run = (t: ExecutionContext, page: Page) => Promise<void>;14 unmodified linesmodified:test/hooks.ts+66 added
600 unmodified lines601 .text();602 603 t.is(response, expectedResponse);604 });605+606+test('runs beforeError before throwing HTTPError', async t => {607+ const server = await createHttpTestServer();608+ server.post('/', (_request, response) => {609+ response.status(500).send();610+ });611+612+ await t.throwsAsync(613+ ky.post(server.url, {614+ hooks: {615+ beforeError: [616+ (error: HTTPError) => {617+ const {response} = error;618+619+ if (response?.body) {620+ error.name = 'GitHubError';621+ error.message = `${response.statusText} --- (${response.status})`.trim();622+ }623+624+ return error;625+ },626+ ],627+ },628+ }),629+ {630+ name: 'GitHubError',631+ message: 'Internal Server Error --- (500)',632+ },633+ );634+635+ await server.close();636+});637+638+test('beforeError can return promise which resolves to HTTPError', async t => {639+ const server = await createHttpTestServer();640+ const responseBody = {reason: 'github down'};641+ server.post('/', (_request, response) => {642+ response.status(500).send(responseBody);643+ });644+645+ await t.throwsAsync(646+ ky.post(server.url, {647+ hooks: {648+ beforeError: [649+ async (error: HTTPError) => {650+ const {response} = error;651+ const body = await response.json() as {reason: string};652+653+ if (response?.body) {654+ error.name = 'GitHubError';655+ error.message = `${body.reason} --- (${response.status})`.trim();656+ }657+658+ return error;659+ },660+ ],661+ },662+ }),663+ {664+ name: 'GitHubError',665+ message: `${responseBody.reason} --- (500)`,666+ },667+ );668+669+ await server.close();670+});modified:readme.md+27 added
256 unmodified lines257 }258 });259 ```260 261+###### hooks.beforeError262+263+Type: `Function[]`\264+Default: `[]`265+266+This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a `HTTPError` as an argument and should return an instance of `HTTPError`.267+268+```js269+import ky from 'ky';270+271+await ky('https://example.com', {272+ hooks: {273+ beforeError: [274+ error => {275+ const {response} = error;276+ if (response && response.body) {277+ error.name = 'GitHubError';278+ error.message = `${response.body.message} (${response.statusCode})`;279+ }280+281+ return error;282+ }283+ ]284+ }285+});286+```287+288 ###### hooks.afterResponse289 290 Type: `Function[]`\291 Default: `[]`329 unmodified lines