krasimir / navigo

A simple vanilla JavaScript router.
MIT License
2.75k stars 250 forks source link

Error crashes Navigo #306

Closed plaul closed 2 years ago

plaul commented 3 years ago

``If an error is thrown inside one of the routes Navigo crashes. Is there a way (official or unofficial) to add a "global" error handler to prevent this? See demo below:

window.addEventListener("load", () => {
  const router = new Navigo("/", { hash: true });
  router
      .on({
        "/": () => console.log("Home"),
        "/about": () => console.log("About"),
      })
      .notFound(() => {
        throw new Error("UPPPPPS")
      })
      .resolve()
});
krasimir commented 3 years ago

I would not rely on the router for such things. Mainly because the error handling needs to happen on a place where could be handled. This is very often the view layer. Anyways, I would go with something like:

function guardRouteHandler(handler) {
  try {
    return (...args) => handler(...args);
  } catch(err) {
    // process the error
  }
}

router.on('/a', guardRouteHandler(handlerA));
router.on('/b', guardRouteHandler(handlerB));
plaul commented 3 years ago

Hi Krasimir

I agree with what you write, but if you "forget" to handle the error then the problem is that your site crashes. But, as a final check the suggested solution definitely seems like a viable way to go

Thanks for the response :-)

plaul commented 2 years ago

Closed as per discusion above