URI::InvalidURIError
RubyERRORNotableParsing

String is not a valid URI

Quick Answer

Validate URIs with URI.parse inside a rescue block before using them; use URI.encode_www_form_component for dynamic path segments.

What this means

Raised by URI.parse when the input string cannot be parsed as a valid URI. Common when handling user-supplied URLs or building URIs from dynamic components.

Why it happens
  1. 1URL contains unencoded spaces or special characters
  2. 2Input is not a URL at all (e.g., a plain hostname)
  3. 3Malformed scheme (e.g., "http:/example.com")

Fix

Validate with rescue before use

Validate with rescue before use
require 'uri'

def valid_uri?(str)
  URI.parse(str)
  true
rescue URI::InvalidURIError
  false
end

Why this works

Wrapping URI.parse in a rescue and returning a boolean lets callers handle invalid input gracefully.

Code examples
Reproducing the errorruby
URI.parse('not a valid url !!!')
# URI::InvalidURIError: URI must be ascii only
Encode user input before parsingruby
safe_url = URI.encode_www_form_component(user_input)
uri = URI.parse("https://example.com/search?q=#{safe_url}")
Rescue in request handlingruby
begin
  uri = URI.parse(params[:url])
rescue URI::InvalidURIError
  render json: { error: 'Invalid URL' }, status: 400
end
Sources
Official documentation ↗

Ruby Standard Library Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Ruby errors