Net::HTTPError
RubyERRORNotableNetwork

HTTP response indicated an error

Quick Answer

Check response.code and response.message on Net::HTTPResponse; rescue Net::HTTPError for all HTTP-level failures.

What this means

Base class for HTTP-level errors in the Net::HTTP standard library. Includes Net::HTTPFatalError (5xx responses) and Net::HTTPRetriableError (3xx/4xx that should be retried). Distinct from socket-level errors.

Why it happens
  1. 1Server returned a 4xx or 5xx status code while using Net::HTTP exception mode
  2. 2Following a redirect that results in an error response

Fix

Check response code explicitly

Check response code explicitly
require 'net/http'

response = Net::HTTP.get_response(URI('https://api.example.com/data'))
case response
when Net::HTTPSuccess
  JSON.parse(response.body)
when Net::HTTPUnauthorized
  raise AuthError, '401 Unauthorized'
when Net::HTTPServerError
  raise ServerError, "#{response.code} #{response.message}"
end

Why this works

Pattern matching on Net::HTTP response classes lets you handle each status range specifically.

Code examples
Rescue all Net::HTTP errorsruby
begin
  response = http.get('/resource')
rescue Net::HTTPError => e
  puts "HTTP error: #{e.message}"
rescue SocketError, Errno::ECONNREFUSED => e
  puts "Connection error: #{e.message}"
end
Response class hierarchy checkruby
Net::HTTPSuccess.superclass      # => Net::HTTPResponse
Net::HTTPClientError.superclass  # => Net::HTTPResponse
OpenURI usageruby
require 'open-uri'
begin
  URI.open('http://example.com/404')
rescue OpenURI::HTTPError => e
  puts e.io.status   # => ["404", "Not Found"]
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