Error crashes Navigo
plaul opened this issue · 3 comments
plaul commented
``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
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
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
Closed as per discusion above