Tidier HTTP error responses in Rails controllers

27 07 2009

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 :


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

Actions

Informations

One response to “Tidier HTTP error responses in Rails controllers”

4 08 2009
Ennuyer.net » Blog Archive » Rails Reading - August 4, 2009 (13:14:34) :

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

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>