2xx status codes other than 200 also mean success

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the web-development category.

Last Updated: 2024-04-18

Status codes other than 200 still mean success

I had the following code for creating an entry on a remote mailing list API:

if response.code == '200'
  JSON.parse(response.read_body)
else
  raise "SendInBlue returned status code #{response.code}"
end

When I ran it, it successfully added an email on the service provider side. Yet my code threw an exception. This was a bug of my own creation. Their response code was 201 (which means "resource created").

I should have considered all 2xx responses successful in my code:

# Consider all 2xx responses successful
if response.code[0] == '2'
  ...
end