You can place a button like <button onclick="window.history.back(); return false;">Go back</button>
inside the 404 page you intend to display whenever such an error occurs while you are logged in and that will take you back to the previous correct page before the 404 error occurred and all the variables will still be present.