Skip to content

Commit

Permalink
Reject normalization errors with CancelableRequest (#1035)
Browse files Browse the repository at this point in the history
  • Loading branch information
callmehiphop authored and szmarczak committed Jan 23, 2020
1 parent d222164 commit fddecab
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
12 changes: 12 additions & 0 deletions source/as-promise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ const parseBody = (body: Buffer, responseType: NormalizedOptions['responseType']
throw new TypeError(`Unknown body type '${responseType as string}'`);
};

export function createRejection(error: Error): CancelableRequest<never> {
const promise = Promise.reject(error) as CancelableRequest<never>;
const returnPromise = (): CancelableRequest<never> => promise;

promise.json = returnPromise;
promise.text = returnPromise;
promise.buffer = returnPromise;
promise.on = returnPromise;

return promise;
}

export default function asPromise<T>(options: NormalizedOptions): CancelableRequest<T> {
const proxy = new EventEmitter();
let body: Buffer;
Expand Down
4 changes: 2 additions & 2 deletions source/create.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Merge} from 'type-fest';
import asPromise from './as-promise';
import asPromise, {createRejection} from './as-promise';
import asStream, {ProxyStream} from './as-stream';
import * as errors from './errors';
import {normalizeArguments, mergeOptions} from './normalize-arguments';
Expand Down Expand Up @@ -126,7 +126,7 @@ const create = (defaults: Defaults): Got => {
throw error;
} else {
// @ts-ignore It's an Error not a response, but TS thinks it's calling .resolve
return Promise.reject(error);
return createRejection(error);
}
}
/* eslint-enable @typescript-eslint/return-await */
Expand Down
5 changes: 5 additions & 0 deletions test/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,11 @@ test('errors are thrown directly when options.stream is true', t => {
});
});

test('normalization errors using convenience methods', async t => {
const url = 'undefined/https://example.com';
await t.throwsAsync(got(url).json().text().buffer(), `Invalid URL: ${url}`);
});

// Fails randomly on Node 10:
// Blocked by https://github.com/istanbuljs/nyc/issues/619
// eslint-disable-next-line ava/no-skip-test
Expand Down

0 comments on commit fddecab

Please sign in to comment.