Search code examples
javascriptbrowserchromium

FetchAPI Response on DNS failure


I am trying something like:

const resp = await fetch('http://bad-domain'); //bad-domain does not resolve

I am then catching an exception later in my code that reads: TypeError: failed to fetch

Is this the expected result of a failed DNS lookup or is this due to resp coming out as different from the normal Response object that an error free fetch returns.

It is just that TypeError does not clearly indicate that the issue is a bad network request and not bad javascript code.


Solution

  • It's the expected behavior:

    12.3. If response is a network error, then reject p with a TypeError and terminate these substeps.

    ...where p is the promise returned by fetch. The specification doesn't require any specific information be provided about why the request failed, just that it failed (at the network level; it doesn't reject on HTTP errors, as I describe here on my old anemic blog, you have to check that on the fulfillment path).