1

What is the proper way to define a catch all route to handle 404 in can.js in a way that all the correct routes will be checked against first? If non are matched this route will catch it and I can display a 404 message.

ramblinjan
  • 6,578
  • 3
  • 30
  • 38
a11hard
  • 1,904
  • 4
  • 19
  • 41

2 Answers2

0

These are just some things I learned diving into the source and doing some tests...

If I defined a root with a single param, for example can.route(":section") and enter into the address bar a fragment that looks like "!#toronto/something/feasf" and there isn't another route to match it, can will currently consider that as the above route and convert it "!#toronto%23something%23else" which is according to the tests generated for that route is correct.

The way to prevent that behavior is defining the route with a trailing slash, can.route(":section/") which when tested agaist the false route should rewrite it to the first match "toronto". The same applies if you define your routes in a control.

You have to catch an invalid param in your route handler or if it is supplied to a model, you can handle the error in the callback. But I think that is pretty clear from the get go.

If you still want to catch an incorrect route for whatever reason, I've made the following test to catch the invalid route. I don't suggest it since it does create unnecessary overhead in your application.

can.route.bind('change', function(ev, newVal) {
    if (newVal === 'route') {
        var valid = false;
        $.each(can.route.routes, function(k,v) {
            if (new RegExp(v.test).test(window.location.hash)){
                valid = true;
                return; //exit loop
            }
        })

        if (!valid) {
            //handle the false route here
        }
    }
});
a11hard
  • 1,904
  • 4
  • 19
  • 41
0

You can register a wildcard after all your routes

// Catch 404
router.register('.*', 'controller#action');
Eric Saboia
  • 1,224
  • 12
  • 14