Detecting Navigation Failures — Transcript

Transcript of the free Vue.js lesson Detecting Navigation Failureswatch the video lesson.

Every once in a while, navigations with View Router can fail. And there are several different reasons that it could do so. One, users could already be on the page that they're trying to navigate to. This has actually occurred to me a decent number of times.

Or sometimes a route guard aborts the navigation by returning false. Another possibility is that a new navigation guard takes place while the previous one hasn't finished. Or sometimes a navigation guard redirects somewhere else by returning a new location. Lastly, navigation will also fail when a navigation guard throws an error.

Well, it's possible to detect all these types of failures and react accordingly. So in this lesson, let's see how we can do that. First, let's trigger one of those failures. I'll create a button on the home page labeled Trigger Router Error.

And onClick, we'll call a method called triggerRouterError. Of course, when you're catching your router errors, it won't be quite so on the nose as triggerRouterError. But you get the idea. push to navigate to the same page that we're already on.

That is the home page. In order to get the result of this, we'll need to use async away, as route navigations are always asynchronous. The result here will either be navigation failure when things don't go as planned, or a falsy value, typically undefined, if everything went well. So that means that we could use a conditional like this.

Cool. Maybe now we can also be just a little bit more accurate in our naming convention. So I'll rename result to navigationFailure. Under the hood, all navigation failures really are are just error instances with a few extra properties to let us know what navigation was prevented and why.

So to check the nature of the navigation result, we can use the is navigation failure function and the navigation failure type from the view router package. Notice that we checked for the type of duplicated here. That is indeed the type of failure that we triggered. Other types, though, include aborted, which means that false was returned inside of a navigation guard.

Or another option would be canceled, which means that a new navigation took place before the current navigation could finish. push was called while waiting inside of a navigation guard. Cool. Lastly, we can also access information about the route navigated to and the route navigated away from on the navigation failure.

And those include all the information that you're used to seeing on the to and from routes, such as the name, the params, the full path, and so on. Let's just console log those so you can see what they look like. Oh, and we'll have to change canceled here back to duplicated so that the console logs will show. Yeah, it looks like the typical information on a route.