errors.ts
This file
Path
test/errors.ts
321 lines · 9.4 KiB · TypeScript
Last changed by
RefactorSindre Sorhusbefore adoptiona5ed57b
History of this fileTake it
RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1–321why, one step back1import {runInNewContext} from 'node:vm';2import test from 'ava';3import ky, {4 ForceRetryError,5 KyError,6 NetworkError,7 ResponseSizeError,8 SchemaValidationError,9 TimeoutError,10 isForceRetryError,11 isHTTPError,12 isKyError,13 isNetworkError,14 isResponseSizeError,15 isTimeoutError,16} from '../source/index.js';17import {NonError} from '../source/errors/NonError.js';18import isRawNetworkError from '../source/utils/is-network-error.js';19import delay from '../source/utils/delay.js';2021const url = 'https://example.com/resource';2223// Safari reports a network failure as a `TypeError` without a stack.24const createStacklessTypeError = (message: string): TypeError => {25 const error = new TypeError(message);26 error.stack = undefined;27 return error;28};2930// NonError3132test('NonError uses a thrown string as its message', t => {33 const error = new NonError('Connection reset');3435 t.is(error.message, 'Connection reset');36 t.is(error.value, 'Connection reset');37 t.is(error.name, 'NonError');38});3940test('NonError uses a default message for a value without a message', t => {41 const error = new NonError(42);4243 t.is(error.message, 'Non-error value was thrown');44 t.is(error.value, 42);45});4647test('NonError ignores a `message` property that is not a string', t => {48 const value = {message: 42};49 const error = new NonError(value);5051 t.is(error.message, 'Non-error value was thrown');52 t.is(error.value, value);53});5455test('NonError falls back to the default message when reading `message` throws', t => {56 const value = {57 get message(): string {58 throw new Error('Getter exploded');59 },60 };6162 const error = new NonError(value);6364 t.is(error.message, 'Non-error value was thrown');65 t.is(error.value, value);66});6768test('NonError.wrap returns any Error as-is, including one from another realm and a DOMException', t => {69 const nonError = new NonError('already wrapped');7071 for (const error of [72 new TypeError('local'),73 runInNewContext('new Error("foreign")') as Error,74 new DOMException('Aborted', 'AbortError'),75 nonError,76 ]) {77 t.is(NonError.wrap(error), error);78 }79});8081test('NonError.wrap wraps values that are not errors', t => {82 const object = {message: 'object message'};8384 for (const [value, message] of [85 ['a string', 'a string'],86 [object, 'object message'],87 [undefined, 'Non-error value was thrown'],88 ] as const) {89 const wrapped = NonError.wrap(value);9091 t.true(wrapped instanceof NonError);92 t.is((wrapped as NonError).value, value);93 t.is(wrapped.message, message);94 }95});9697// ForceRetryError9899test('ForceRetryError accepts an infinite delay', t => {100 t.is(new ForceRetryError({delay: Number.POSITIVE_INFINITY}).customDelay, Number.POSITIVE_INFINITY);101});102103test('ForceRetryError without a cause has no own `cause` property', t => {104 t.false(Object.hasOwn(new ForceRetryError({code: 'RATE_LIMIT'}), 'cause'));105 t.false(Object.hasOwn(new ForceRetryError(), 'cause'));106});107108// HTTPError109110test('HTTPError message includes a custom request method', async t => {111 const error = await t.throwsAsync(ky(url, {112 method: 'PROPFIND',113 retry: 0,114 fetch: async () => new Response('', {status: 423, statusText: 'Locked'}),115 }));116117 t.true(isHTTPError(error));118 t.is(error?.message, `Request failed with status code 423 Locked: PROPFIND ${url}`);119});120121// Other error classes122123test('TimeoutError message includes the request method and URL', t => {124 const request = new Request(url, {method: 'DELETE'});125 const error = new TimeoutError(request);126127 t.is(error.message, `Request timed out: DELETE ${url}`);128 t.is(error.request, request);129});130131test('ResponseSizeError message includes the limit, method, and URL', t => {132 const request = new Request(url, {method: 'POST', body: 'x'});133 const error = new ResponseSizeError(request, 1024);134135 t.is(error.message, `Response body exceeded 1024 bytes: POST ${url}`);136 t.is(error.request, request);137 t.is(error.maxResponseSize, 1024);138});139140test('KyError is a branded base error with its own name', t => {141 const error = new KyError('Something in Ky failed');142143 t.is(error.name, 'KyError');144 t.is(error.message, 'Something in Ky failed');145 t.true(error instanceof Error);146 t.true(isKyError(error));147});148149// Type guards150151test('type guards require the brand to be exactly `true`', t => {152 for (const brand of [1, 'true', {}]) {153 const error = Object.assign(new Error('Look-alike'), {name: 'HTTPError', isKyError: brand});154155 t.false(isHTTPError(error), `brand: ${JSON.stringify(brand)}`);156 t.false(isKyError(error), `brand: ${JSON.stringify(brand)}`);157 }158});159160test('isKyError accepts every Ky error class and any value carrying the exact brand', async t => {161 const request = new Request(url);162 const httpError = await t.throwsAsync(ky(url, {163 retry: 0,164 fetch: async () => new Response('', {status: 500}),165 }));166167 for (const error of [168 httpError,169 new KyError('base'),170 new NetworkError(request),171 new TimeoutError(request),172 new ResponseSizeError(request, 1),173 new ForceRetryError(),174 // A copy of Ky in another realm or a duplicated dependency is only recognisable by the brand.175 runInNewContext('Object.assign(new Error("foreign"), {isKyError: true})') as Error,176 {isKyError: true},177 ]) {178 t.true(isKyError(error), `name: ${String((error as {name?: string}).name)}`);179 }180181 for (const value of [new NonError('thrown'), new SchemaValidationError([{message: 'Invalid'}]), {isKyError: 'true'}]) {182 t.false(isKyError(value));183 }184});185186test('type guards return false for values that are not objects', t => {187 for (const value of [undefined, 0, '', 'HTTPError', true]) {188 t.false(isKyError(value));189 t.false(isHTTPError(value));190 t.false(isNetworkError(value));191 t.false(isTimeoutError(value));192 t.false(isForceRetryError(value));193 t.false(isResponseSizeError(value));194 }195});196197// Raw network error detection198199test('recognizes every exact runtime network error message', t => {200 for (const message of [201 'network error',202 'NetworkError when attempting to fetch resource.',203 'The Internet connection appears to be offline.',204 'Network request failed',205 'fetch failed',206 'terminated',207 ' A network error occurred.',208 'Network connection lost',209 'Failed to fetch',210 ]) {211 t.true(isRawNetworkError(new TypeError(message)), `message: ${JSON.stringify(message)}`);212 }213});214215test('does not recognize look-alike network error messages', t => {216 for (const message of [217 'A network error occurred.',218 'Network Error',219 'Fetch failed',220 'fetch failed.',221 'Failed to fetch dynamically imported module: https://example.com/chunk.js',222 'Failed to fetch (example.com',223 'NetworkError',224 '',225 ]) {226 t.false(isRawNetworkError(new TypeError(message)), `message: ${JSON.stringify(message)}`);227 }228});229230test('recognizes Chrome `Failed to fetch` with a hostname', t => {231 t.true(isRawNetworkError(new TypeError('Failed to fetch (api.example.com)')));232});233234test('recognizes a stacked Safari `Load failed` captured by Sentry', t => {235 t.true(isRawNetworkError(Object.assign(new TypeError('Load failed'), {__sentry_captured__: true})));236 t.true(isRawNetworkError(Object.assign(new TypeError('Load failed (api.example.com)'), {__sentry_captured__: true})));237});238239test('does not recognize Safari `Load failed` look-alikes without a stack', t => {240 for (const message of ['Load failed (api.example.com', 'Load failed: script error', 'load failed']) {241 t.false(isRawNetworkError(createStacklessTypeError(message)), `message: ${JSON.stringify(message)}`);242 }243});244245test('recognizes Deno network errors only by their prefix', t => {246 t.true(isRawNetworkError(new TypeError('error sending request for url (https://example.com/): client error (Connect): tcp connect error: Connection refused (os error 61)')));247 t.false(isRawNetworkError(new TypeError('Upload failed: error sending request for url (https://example.com/)')));248});249250// How Ky turns raw fetch errors into `NetworkError`251252test('a network TypeError from another realm becomes a NetworkError with that cause', async t => {253 const foreignError = runInNewContext('new TypeError("fetch failed")') as TypeError;254 t.false(foreignError instanceof TypeError);255256 const error = await t.throwsAsync(ky(url, {257 retry: 0,258 async fetch() {259 throw foreignError;260 },261 }), {instanceOf: NetworkError});262263 t.is(error?.cause, foreignError);264});265266test('a NetworkError from a body read reports the request that was sent', async t => {267 let sent: Request | undefined;268 const cause = new TypeError('terminated');269270 const error = await t.throwsAsync(ky(url, {271 retry: {limit: 1, delay: () => 0},272 async fetch(request) {273 sent = request as Request;274 return new Response(new ReadableStream({275 start(controller) {276 controller.error(cause);277 },278 }));279 },280 }).text(), {instanceOf: NetworkError});281282 t.is(error?.request, sent);283 t.is(error?.cause, cause);284});285286// `beforeError` processing287288test('`beforeError` hooks pass a replacement along and a non-Error result does not undo it', async t => {289 const replacement = new Error('Replaced');290 const seen: Error[] = [];291292 const error = await t.throwsAsync(ky(url, {293 retry: 0,294 fetch: async () => new Response('', {status: 500}),295 hooks: {296 beforeError: [297 () => replacement,298 ({error}) => {299 seen.push(error);300 return 'not an error' as never;301 },302 ({error}) => {303 seen.push(error);304 },305 ],306 },307 }));308309 t.is(error, replacement);310 t.deepEqual(seen, [replacement, replacement]);311});312313// `delay`314315test('delay rejects with the reason of an already aborted signal', async t => {316 const reason = new Error('Already aborted');317318 const error = await t.throwsAsync(delay(0, {signal: AbortSignal.abort(reason)}));319320 t.is(error, reason);321});