Aborting turbo on request fail

Currently if there’s a 400 or other such error on a link on a simple rails app out of the box, the page just refreshes (rails 8). There doesn’t seem to be away to do ‘event.stop’ or similar from within an event listener on stuff like turbo:submit-end or error or anything like that. It just reloads the whole page which is dumb and there’s no way to pop up a nice error message.

Here’s how I’m tackling it with a giant monkeypatch hack but is there a better way? I’m hooking into the turbo ‘pageInvalidated’ method, which is called if the resulting page doesn’t have a turbo ‘reload’ header. This is incorrectly using a global and maybe there’s a way to attach this to the current instance of the renderer or something.

in application.js

let reloadPage = true;

Object.defineProperty(Turbo.navigator.adapter, 'pageInvalidated', {
    value: function(reason) {
        if (reloadPage) {
            this.reload(reason);
        } else {
            console.log("Not reloading page, ", reason)
        }
    }
})

addEventListener('turbo:submit-end', (event) => {
    if (event.detail.success == false) {
         // do something nice here
        alert("Request failed: " + event.detail.fetchResponse.response.status);
        reloadPage = false;
    }
});