Custom error handler
Every navigation will either succeed, will be cancelled, or will error. There are two ways to observe this.
The router.events observable will emit:
NavigationStart
when navigation starsNavigationEnd
when navigation succeedsNavigationCancel
when navigation is canceledNavigationError
when navigation fails
All of them contain the id property we can use to group the events associated with a particular navigation.
If we call
router.navigate
or
router.navigateByUrl
directly, we will get a promise that:
- will be resolved with true if the navigation succeeds
- will be resolved with false if the navigation gets cancelled
- will be rejected if the navigation fails
Navigation fails when the router cannot match the URL or an exception is thrown during the navigation. Usually this indicates a bug in the application, so failing is the right strategy, but not always. We can provide a custom error handler to recover from certain errors as shown in the following code:
function treatCertainErrorsAsCancelations...