How to handle 'no route matched' in Ember.js and show 404 page?

后端 未结 5 414
无人共我
无人共我 2020-12-08 18:55

How can I handle the error

Uncaught Error: No route matched the URL \'...\'

and show a custom 404 page?


Note: This questi

5条回答
  •  忘掉有多难
    2020-12-08 19:25

    Here is an example:

    I define the last route in my router using a wildcard route see: http://emberjs.com/guides/routing/defining-your-routes/#toc_wildcard-globbing-routes

    I have a /not-found route, see last route defined in my router /*path to catch any text string, see: https://github.com/pixelhandler/blog/blob/master/client/app/router.js#L19

    Router.map(function () {
      this.route('about');
      this.resource('posts', function () {
        this.resource('post', { path: ':post_slug' });
      });
      this.resource('admin', function () {
        this.route('create');
        this.route('edit', { path: ':edit_id' });
      });
      this.route('not-found', { path: '/*path' });
    });
    

    That route does a redirect to /not-found, see: https://github.com/pixelhandler/blog/blob/master/client/app/routes/not-found.js

    import Ember from 'ember';
    export default Ember.Route.extend({
      redirect: function () {
        var url = this.router.location.formatURL('/not-found');
        if (window.location.pathname !== url) {
          this.transitionTo('/not-found');
        }
      }
    });
    

    Also any route having a hook (e.g. model, beforeModel, afterModel) that results in a rejected promise, can use the error action to transition to the 404.

    actions: {
      error: function (error) {
        Ember.Logger.error(error);
        this.transitionTo('/not-found');
      }
    }
    

    Which renders a not-found template, see: https://github.com/pixelhandler/blog/blob/master/client/app/templates/not-found.hbs

    404 Not Found

    Perhaps you have a link that has changed, see {{#link-to 'posts'}}Archives{{/link-to}}.

    Here is my 404 page: http://pixelhandler.com/not-found

提交回复
热议问题