I have this code (view on JSFiddle):
fetch('https://some.invalid.url').then(resp => resp.text())
.catch(err => console.log("got error: " + err))
.then(text => console.log("got text: " + text));
Currently this logs the two lines
"got error: TypeError: Failed to fetch"
"got text: undefined"
I would like it to only log the line
"got error: TypeError: Failed to fetch"
In other words, I would like the promise chain to end once the .catch
is called and not go into the .then
. How can I do this?
(I could throw an exception inside the .catch
, but I think that results in a unhandledrejection
event which is undesirable).
2
Answers
Your issue is that your
.catch()
returns a resolved promise (resolving with the return value ofconsole.log()
, ieundefined
).Either move the
.catch()
to the end of the promise chainor have it continue rejecting the chain (but note this will throw an uncaught promise rejection error)
You need to swap the ordering so the
.catch()
is at the end of the chain.(view on JSFiddle)