Rails 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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
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 |
One thought on “Tidier HTTP error responses in Rails controllers”