Vue-router: Throw error for non existent route

Created on 30 Aug 2017  路  4Comments  路  Source: vuejs/vue-router

What problem does this feature solve?

When using router.push() if the path does not match any route, the router doesn't throw any error.

It's more obvious when you click a <router-link> and nothing happens, but when the route change is done after some auth procedure it's not clear where the problem lies. You don't know if there is a typo on your path, or if the error is somewhere else.

There should be a way to know when these cases happen, at the very least in dev mode.

I've tried using router.onError() but apparently a missing route is not considered an error.

What does the proposed API look like?

It should be as simple as throwing the error to router.onError(). No need to modify the API.

feature request

Most helpful comment

Adding a path: '*' route for a web app makes sense, but I'm working on Vue app that runs on Cordova, Electron, and Chrome OS so a 404 kind of page doesn't make sense.

I will add it anyway as a workaround, but IMO trying to reach an inexistent route should be considered en error and there should be a way to catch those errors.

All 4 comments

We could also warn if the route doesn't match anything but keep in mind that we use a path: '*', the warning will never appear, the page will instead change routes to a (usually) 404.
So, for the moment, adding a route with path: '*' and making it point to an error page should do it

Adding a path: '*' route for a web app makes sense, but I'm working on Vue app that runs on Cordova, Electron, and Chrome OS so a 404 kind of page doesn't make sense.

I will add it anyway as a workaround, but IMO trying to reach an inexistent route should be considered en error and there should be a way to catch those errors.

I鈥檓 adding a name to every single route so that the vue-router can report dead links by specifying router-link by their names, but such a scheme would not necessary at all if the non-existent paths throw errors, or if they say something in console at least...

Non-existent named routes will fail but when using a string location or a path, the router will still generate a valid location so they can be consumed by a router-link. If you want any non-existent link to throw, establish a guard:

router.beforeEach((to, from, next) => {
  if (!to.matched.length) next(new Error(`Location "${to.fullPath}" does not exist`))
  else next()
})
Was this page helpful?
0 / 5 - 0 ratings

Related issues

shinygang picture shinygang  路  3Comments

yyx990803 picture yyx990803  路  3Comments

druppy picture druppy  路  3Comments

posva picture posva  路  3Comments

achen224 picture achen224  路  3Comments