如何处理错误
Uncaught Error: No route matched the URL '...'
并显示自定义的404页面?
注意:这个问题之前已经被问过并且回答了几个月前 - 但是现在不再起作用。
App.Router.map(function() {
//set up all of your known routes, and then...
this.route("fourOhFour", { path: "*path"});
});
您可以定义FourOhFourRoute来显示您选择的“找不到路由”消息。在fourOhFour路由中,您可以通过路径参数访问最初请求的路径。
编辑:仅为澄清-此答案是在其他答案被报告无法使用后提供的。
编辑2:我已经更新了答案以反映Yehuda Katz的评论(如果我有错误,请让我知道)。
以下是一个例子:
我使用通配符路由定义我的路由器中的最后一条路线,请参阅:http://emberjs.com/guides/routing/defining-your-routes/#toc_wildcard-globbing-routes
我有一个/not-found
路由,参见我路由器中定义的最后一个路由/*path
,以捕获任何文本字符串,请参阅: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' });
});
该路由重定向到/not-found
,请参见: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');
}
}
});
任何具有钩子(例如model
、beforeModel
、afterModel
)的路由,如果导致一个被拒绝的承诺,可以使用error
操作来转换到404页面。
actions: {
error: function (error) {
Ember.Logger.error(error);
this.transitionTo('/not-found');
}
}
这将呈现一个 not-found
模板,请参见:https://github.com/pixelhandler/blog/blob/master/client/app/templates/not-found.hbs
<h1>404 Not Found</h1>
<p>
Perhaps you have a link that has changed, see {{#link-to 'posts'}}Archives{{/link-to}}.
</p>
这是我的404页面:http://pixelhandler.com/not-found
App.Router.map(function() {
this.resource('post', ...);
this.resource('user', ...);
this.route('catchAll', { path: '/*' });
});
App.CatchAllRoute = ...
在Ember 2.x中
在App.Router.map
函数内,将下面的代码放在回调函数的末尾。
this.route('your_handler_route_name', { path: '/*path' });
your_handler_route_name
路由捕获。解决方案1
显示404内容:
App.Router.reopen({
handleURL: function (url) {
try {
return this._super(url);
} catch (error) {
if (error.message.match(/No route matched the URL/)) {
return this._super('/404');
}
}
}
});
App.Router.reopen({
location: locationImplementation,
handleURL: function (url) {
try {
return this._super(url);
} catch (error) {
if (error.message.match(/No route matched the URL/)) {
this.transitionTo('404');
return this._super('/404');
}
}
}
});
App.Router.router.recognizer.hasRoute('route.path.goes.here');
检查路由或资源是否存在。
:
不是必需的,但参数名是必需的(这样你就可以从路由中获取它)。我使用*path
。 - Yehuda Katz