How to fallback to secondary window.location url redirect if file not found for original redirect

I am using Swiper JS to create a series of locally hosted thumbs galleries as html files. I have an index page that acts as the global location to navigate into any particular thumbs gallery. I would also like to add the functionality that if you are already inside one of the thumbs galleries (One.html) when you get to the end use the On reachEnd parameter in Swiper JS and jump to the next html in sequence. I am using javascript to get the file path of the active html file when reachEnd is activated, I then parse the file path to get the file name, increment the characters at the end of the file name, concatenate the string back together and use the window.location(newpath) action to redirect to the new url.

I have this working but the problem I cannot seem to figure out is how to handle the situation where I am either at the very first or very last html file. When the on reachEnd parameter is triggered I want to redirect back to the Index.html if the newly incremented file path cannot be found.

I was trying to use a function like this as a fallback for when the file cannot be found but the function does not catch the error and continues to try and open the failing url instead of the redirect.

example.com and fallback.com are replaced with my own concatenated paths and I have also tested directly by using file names I know exist. In both cases it dismisses the fallback redirect.

How do I enforce a redirect when the originalUrl cannot be found.

function redirectToUrl(originalUrl, fallbackUrl) {
  try {
    // Attempt to redirect to the original URL
    window.location.href = originalUrl;
  } catch (error) {
    // If an error occurs (e.g., URL not found), redirect to the fallback URL
    window.location.href = fallbackUrl;
  }
}

// Example usage:
redirectToUrl("https://example.com", "https://fallback.com");