NodeJS 18 has an experimental support for fetch
https://nodejs.org/dist/latest-v18.x/docs/api/globals.html
fetch
function throws FetchError
instances which I need to analize in try-catch
with instanceof
check... Unfortunately, FetchError
class is not exposed in the global space of NodeJS!
I understand the API is "experimental" but, seriously, is there a way to access that class? Ideal answer will compile in TypeScript as well 😉
P.S. one workaround is error.name == "FetchError"
but I'm still curious about the class. Why it's not exposed?
I agree it's painful to not have a simple way to analyze errors.
What I'm doing in TypeScript when fetch()
is throwing and I target a specific code error (in this case ENETUNREACH
):
import { FetchError } from 'node-fetch';
try {
await fetch('...');
} catch (error) {
if (error instanceof Error && (error.cause as FetchError)?.code === 'ENETUNREACH') {
...
} else {
throw error;
}
}