Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URI::InvalidURIError (URI must be ascii only)

I have a legacy rails 3.2 app, when I try to hit a route with a none-ascii char e.g; example.com/city/bergstraße then I get the following error:

/Users/user/.rvm/rubies/ruby-2.2.5/lib/ruby/2.2.0/uri/rfc3986_parser.rb:20:in `split'
/Users/user/.rvm/rubies/ruby-2.2.5/lib/ruby/2.2.0/uri/rfc3986_parser.rb:72:in `parse'
/Users/user/.rvm/rubies/ruby-2.2.5/lib/ruby/2.2.0/uri/common.rb:226:in `parse'
actionpack (3.1.0) lib/action_dispatch/routing/redirection.rb:91:in `block in redirection_proc'
rack-mount (0.8.3) lib/rack/mount/route_set.rb:152:in `call'
rack-mount (0.8.3) lib/rack/mount/route_set.rb:152:in `block in call'
...

The problem is, that I get this error before hitting any controller, so I just wonder where can I catch this error to parse and fix the URL? thanks.

P.S: please have a look to the stacktrace before pointing me to any previous post.

like image 695
tokhi Avatar asked Nov 16 '25 14:11

tokhi


1 Answers

According to RFC 3986 a URI may contain only a subset of ASCII characters.

To provide a valid URI the non-ASCII characters should be escaped:

irb(main):008:0> URI.parse "example.com/city/#{URI.encode('bergstraße')}"
=> #<URI::Generic example.com/city/bergstra%C3%9Fe>

The problem is, that I get this error before hitting any controller, so I just wonder where can I catch this error to parse and fix the URL?

The problem is you should not really be catching this error. Your rails server should not be responsible for responding to bad or malformed requests.

While you could attempt to write a piece of middleware to hack around the issue you should instead figure out why the clients are sending requests for an invalid URI.

If they are originating from your own application make sure you are escaping slug columns properly and not just creating urls with string interpolation. The stringex gem or friendly_id are your friends here.

like image 73
max Avatar answered Nov 18 '25 20:11

max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!