Merb Router:如何返回 406 错误

发布于 2024-08-03 05:37:17 字数 196 浏览 4 评论 0原文

是否可以让路由器返回错误代码(或整个机架响应)以响应匹配的路由?

例如,我已经从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

┼── 2024-08-10 05:37:17

这并不明显,但很有效。

解决方案:

match('/',:query_string=>/.+/).defer_to do |request, params|
  raise Merb::ControllerExceptions::NotAcceptable, 
        "Query String Unknown: #{request.query_string}"
end

说明:

为了触发 406 错误,我们需要引发 Merb::ControllerExceptions::NotAcceptable 但如果我们在设置路由时这样做,则对任何人都没有帮助。相反,我们需要等待 Merb 处理请求。这就是 defer_to 块的作用。当请求到来时,我们会引发错误,并且它会被捕获并处理,就像我们从控制器处理此错误一样。

问题

我最初问题的目标之一是避免必须经历所有的调度开销。相反,此解决方案是通过异常控制器调度的,该控制器的计算成本比 [406,{'content-type'=>'text/plain},['406 Not Acceptable']]

This is not obvious, but it is effective.

Solution:

match('/',:query_string=>/.+/).defer_to do |request, params|
  raise Merb::ControllerExceptions::NotAcceptable, 
        "Query String Unknown: #{request.query_string}"
end

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 the defer_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']]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文