Hotwire Discussion

Catching failed fetch requests due to lost network connection

Hi folks,

Does anybody have any suggestions for how to handle the situation in which the browser’s network connection is offline after the page loads and before a Turbo form submission is triggered?

In my testing it seems that the failure of the fetch request is logged to the console, but there’s not really much else I can do as a Turbo user to recover from the error? I was hoping, for example, that there might be a Turbo event that I could bind to and then gracefully recover (such as by displaying a “Whoops: looks like you’re offline” element).

Any thoughts about how to handle this situation?

Cheers,
Louis.

5 Likes

Did you ever figure this out? I’m trying to find a way to accomplish this same thing.

Something like?:

document.addEventListener(`turbo:before-fetch-response`, (event) => {
  if(event.detail.fetchResponse.response.status === 404) {
    alert("Whoops: looks like you're offline")
    event.preventDefault();
    history.back();
  }
});

Unfortunately turbo:before-fetch-response is only dispatched after a response from the server is available.

It doesn’t seem like turbo dispatches events when the network or remote server is unreachable, it just throws the NetworkError, but it doesn’t seem like Turbo has a simple way to access anything about the fetch attempt in this particular case.

Ah good point. I suggest requesting the feature at Issues · hotwired/turbo · GitHub