Merb Router:如何返回 406 错误
是否可以让路由器返回错误代码(或整个机架响应)以响应匹配的路由?
例如,我已经从 WordPress 转向自制博客解决方案。搜索引擎遇到像“/?tag=ruby
”这样的 URL,需要返回 406 错误。相反,路由器尽职尽责地将它们路由到与“/
”相同的位置,我可以匹配我想要删除的 URL,但我不知道如何处理它们
Is it possible to have the router return an error code (or an entire rack response) in response to a matched route?
E.g. I have move from WordPress to a home grown blogging solution. Search engines are hitting URLs like '/?tag=ruby
' that need to return a 406 error. Instead, the router dutifully routes them to the same place as '/
' I can match the URLs I want to get rid of but I don't know what to do with them
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这并不明显,但很有效。
解决方案:
说明:
为了触发 406 错误,我们需要引发
Merb::ControllerExceptions::NotAcceptable
但如果我们在设置路由时这样做,则对任何人都没有帮助。相反,我们需要等待 Merb 处理请求。这就是 defer_to 块的作用。当请求到来时,我们会引发错误,并且它会被捕获并处理,就像我们从控制器处理此错误一样。问题
我最初问题的目标之一是避免必须经历所有的调度开销。相反,此解决方案是通过异常控制器调度的,该控制器的计算成本比
[406,{'content-type'=>'text/plain},['406 Not Acceptable']]
This is not obvious, but it is effective.
Solution:
Explanation:
In order to trigger a 406 error we need to raise
Merb::ControllerExceptions::NotAcceptable
but if we do this while setting up the routes it helps exactly no one. Instead we need to wait until Merb is handling the request. this is what thedefer_to
block does. When the request comes in we raise the error and it is caught and handled just as it would be if we through this error from a controller.Problems
One of the goals of my original question was to avoid having to go through all of the dispatching overhead. Instead this solution is dispatched through the exceptions controller which more computationally expensive then
[406,{'content-type'=>'text/plain},['406 Not Acceptable']]