Tidier HTTP error responses in Rails controllers
27 07 2009Rails provides some flexible and fairly short controller methods for responding with an HTTP error code. Given that controllers are complicated enough by nature, I’m always looking for ways to DRY them up and make the code easy to understand. So here are some controller methods that make it really easy to provide correct HTTP error responses to clients.
Put this in config/initializers/respond_with_http_errors.rb :
class ActionController::Base
protected
# Display a "400 Bad Request" response based on a determination made by application logic.
def respond_bad_request(message = "Your request was invalid.", options = {})
respond_with_error(400, 'Bad Request', message, options)
end
# Display a "403 Forbidden" response based on a determination made by application logic.
def respond_forbidden(message = "You are not authorized to access that document.", options = {})
respond_with_error(403, 'Forbidden', message, options)
end
# Display a "404 Not Found" response based on a determination made by application logic.
def respond_not_found(message = "The document you requested doesn't exist.", options = {})
respond_with_error(404, 'Not Found', message, options)
end
def respond_with_error(status_code, status_name, message, options)
flash[:error] = message
defaults = { :status => status_code }
respond_to do |format|
format.html { defaults.merge!(:inline => "<h1>#{status_name}</h1><p><%=h flash[:error] %></p>", :layout => true) }
format.json { defaults.merge!(:json => "#{status_name}: #{message}".to_json) }
end
render defaults.merge(options)
end
end






[...] Pervasive Code ยป Tidier HTTP error responses in Rails controllers [...]