简体   繁体   中英

JavaScript fetch ERR_CONNECTION_REFUSED vs TypeError Failed to fetch

When using the JavaScript fetch API, the browser's console logs an error of ERR_CONNECTION_REFUSED , but the catch block of fetch returns a message of TypeError Failed to fetch when a server is offline.

Example

The following minimal fetch highlights the two error messages:

fetch("https://localhost/get-something", {
    method: "POST"
}).then(resp => {
    console.log(resp)
}).catch(err => {
    console.log("ERR:", err, err.name, err.message)
})

When running the fetch, the browser's console will have two errors:

POST https://localhost/get-something net::ERR_CONNECTION_REFUSED

And

ERR: TypeError: Failed to fetch
// err.message will be "failed to fetch"

The generic failed to fetch message from the catch block is returned in instances other than a server being down. I'm more interested in the browser's console error of ERR_CONNECTION_REFUSED .

Question

Is there a way to capture the ERR_CONNECTION_REFUSED value in a failed fetch call?

Unfortunately this is not possible as this kind of message is printed in the console from Chrome itself. Suppressing these types of messages has been debated for years, but the consensus seems to be that these kinds of messages are desirable.

you can only hide them from your client using the filter check this: https://umaar.com/dev-tips/79-hide-network-console/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM