OpenURI::HTTPError
RubyERRORNotableNetwork

HTTP error from OpenURI::open

Quick Answer

Rescue OpenURI::HTTPError and inspect e.io.status for the HTTP code and message.

What this means

Raised by URI.open (OpenURI) when the server returns a non-2xx HTTP status. The exception carries an io attribute with the response body and status.

Why it happens
  1. 1URL returns a 404 Not Found, 403 Forbidden, or 5xx Server Error
  2. 2Redirect chain results in an error response

Fix

Rescue and inspect status

Rescue and inspect status
require 'open-uri'

begin
  content = URI.open('https://api.example.com/data').read
rescue OpenURI::HTTPError => e
  code, msg = e.io.status
  case code
  when '404' then raise NotFoundError
  when '401' then raise AuthError
  else raise RemoteError, "#{code}: #{msg}"
  end
end

Why this works

e.io.status returns a two-element array [code_string, message] from the HTTP response.

Code examples
Reproducing the errorruby
URI.open('https://httpbin.org/status/404')
# OpenURI::HTTPError: 404 Not Found
Accessing response body on errorruby
rescue OpenURI::HTTPError => e
  puts e.io.status   # => ["404", "Not Found"]
  puts e.io.read     # response body, if any
With Faraday instead (recommended)ruby
response = Faraday.get('https://api.example.com/data')
raise "Error #{response.status}" unless response.success?
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