How do you force a script to fire on Page Not Found?

Continuing the discussion from How do you force a script to refire on every page load in Discourse?:

As discussed in the now-closed topic, the code above does fire when a topic is loaded. But I want to trigger a redirection when the Page Not Found page is loaded. Neither api.onPageChange nor $( document ).ready fire on a 404 error. How can I catch a 404 and redirect?