Skip to content

Commit 8806bee

Browse files
author
jarvisjiang
committed
returns a FetchError when the response is not ok
1 parent 835efb9 commit 8806bee

File tree

3 files changed

+26
-5
lines changed

3 files changed

+26
-5
lines changed

src/fetch/defines.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,23 @@ export interface FetchInit extends RequestInit {
5555
* Specifies the maximum time in milliseconds to wait for the fetch request to complete.
5656
*/
5757
timeout?: number;
58+
}
59+
60+
/**
61+
* Represents an error that occurred during a fetch operation when the response is not ok.
62+
*/
63+
export class FetchError extends Error {
64+
/**
65+
* The name of the error.
66+
*/
67+
name = 'FetchError';
68+
/**
69+
* The status code of the response.
70+
*/
71+
status = 0;
72+
73+
constructor(message: string, status: number) {
74+
super(message);
75+
this.status = status;
76+
}
5877
}

src/fetch/fetch.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { Err, Ok } from 'happy-rusty';
22
import invariant from 'tiny-invariant';
33
import { TIMEOUT_ERROR } from './constants.ts';
4-
import type { FetchInit, FetchResponse, FetchTask } from './defines.ts';
4+
import { FetchError, type FetchInit, type FetchResponse, type FetchTask } from './defines.ts';
55

66
/**
77
* Fetches a resource from the network as a text string and returns a `FetchTask` representing the operation.
@@ -160,7 +160,7 @@ export function fetchT<T>(url: string | URL, init?: FetchInit): FetchTask<T> | F
160160

161161
if (!res.ok) {
162162
await res.body?.cancel();
163-
return Err(new Error(`fetch status: ${ res.status }`));
163+
return Err(new FetchError(res.statusText, res.status));
164164
}
165165

166166
switch (responseType) {

tests/fetch.test.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { assert, assertThrows } from '@std/assert';
2-
import { ABORT_ERROR, fetchT, TIMEOUT_ERROR } from '../src/mod.ts';
2+
import { ABORT_ERROR, FetchError, fetchT, TIMEOUT_ERROR } from '../src/mod.ts';
33

44
Deno.test('fetch', async (t) => {
55
const mockServer = 'https://fakestoreapi.com';
@@ -195,8 +195,10 @@ Deno.test('fetch', async (t) => {
195195
}
196196
});
197197

198-
await t.step('Fetch fail', async () => {
198+
await t.step('Fetch not found', async () => {
199199
const err: Error = (await fetchT(mockNotFound)).unwrapErr();
200-
assert(err.message.includes('404'));
200+
assert(err.name === 'FetchError');
201+
assert(err.message === 'Not Found');
202+
assert((err as FetchError).status === 404);
201203
});
202204
});

0 commit comments

Comments
 (0)