Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access FetchError class in NodeJS

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?

like image 700
Ivan Kleshnin Avatar asked Oct 21 '25 04:10

Ivan Kleshnin


1 Answers

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;
    }
}
like image 148
Thomas Ramé Avatar answered Oct 22 '25 18:10

Thomas Ramé