I'm trying to figure out how to handle invalid routes within my application using Ember.Router
.
Currently if I enter an invalid route, e.g. myapp.com/#FooBarDoesntExist, it will redirect to the index route ('/'). I'd like it if I could define a notFound or 404 state that it would route to so I can inform the user what happend. As opposed to them getting dumped on the home page.
Ember.Router in its current version does not provide means to handle unknown routes. Time to hack!
Solution 1 - Quick and dirty
The idea here is the following. We have the
Ember.Router.route(path)
method, which is invoked with the requested (potentially unknown) path. After the invocation of this method, the path of the router is guaranteed to be known. So, if we compare the requested path and the actual path and they differ - then the requested path is invalid and we may redirect a user to the 404 page.This solution is quite expensive. For example, if the current state is "/a/b/c", and a user wants to navigate to "/b/d/e/unknown", the router will dutifully enter known states "b", "d" and "e", and only then we discard the path as unknown. It would be nice if we can tell this before the actual routing starts.
Solution 2 - Fiddling with private methods
Here we check the validity of the given path, and only then tell the router to proceed:
This solution also has its drawback - it uses the
resolvePath
method which is marked as private. Nevertheless, I'd use this solution, since it is more effective than the first one.The recommended way to do this in Ember 1.13 is to create a catch-all route:
Then put your 404 template in
404.hbs
.A good way to handle this problem is to declare a route who map all possible urls in addition to your routes. You can an example here : http://jsfiddle.net/mbreton/r3C9c/
In this example all unknown urls are redirect to index route.