如何捕获routes.rb中的参数错误

发布于 2024-12-11 18:56:24 字数 448 浏览 3 评论 0 原文

在 RAils 应用程序的routes.rb 文件中,我们正在路由一些旧版 URL,如下所示:

get "downloads/item/:slug", :to => redirect {|params| "/downloads/#{params[:slug].gsub('.', '')}"}, :constraints => { :slug => /[^\/]+/ }

但是,问题是其中一些旧版 URL 具有不可编码的字符,例如省略号,这会破坏 gsub 命令出现错误:

NilClass# (ArgumentError)“UTF-8 中的无效字节序列”

我的问题是:如何捕获此异常,以及我的其他异常路线.rb 文件?我认为这与在文件末尾使用“包罗万象”路由到 404 不同。

In a RAils app, in the routes.rb file, we are routing some legacy URLs like so:

get "downloads/item/:slug", :to => redirect {|params| "/downloads/#{params[:slug].gsub('.', '')}"}, :constraints => { :slug => /[^\/]+/ }

However, the problem is some of these legacy URLs have non-encodeable characters, like an ellipsis, that breaks the gsub command with the error:

NilClass# (ArgumentError) "invalid byte sequence in UTF-8"

My question is: How do I catch this exception, and thus other exceptions like so in my routes.rb file? I assume this is different than having the "catch-all" at the end of the file to route to a 404.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

三生路 2024-12-18 18:56:24

如果错误发生在块内,您可以使用 begin..rescue

get "downloads/item/:slug", :to => redirect {|params|
  begin
    "/downloads/#{params[:slug].gsub('.', '')}"
  rescue ArgumentError
    "/"
  end
}, :constraints => { :slug => /[^\/]+/ }

阅读更多内容:http://ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html

If the error happens inside the block, you can use a begin..rescue

get "downloads/item/:slug", :to => redirect {|params|
  begin
    "/downloads/#{params[:slug].gsub('.', '')}"
  rescue ArgumentError
    "/"
  end
}, :constraints => { :slug => /[^\/]+/ }

Read more: http://ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html

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