Getting access to :not_found, :internal_server_err

2019-04-13 00:30发布

问题:

It looks like ActionController::StatusCodes has been removed from Rails 3.

I used synonyms for HTTP status codes such as

200 => :ok
404 => :not_found
500 => :internal_server_error

For more codes, see here:

http://apidock.com/rails/ActionController/Base/render#254-List-of-status-codes-and-their-symbols

Where can I find these in Rails 3?

回答1:

It seems that the error codes reside in action_dispatch/middleware/show_exceptions.rb where the symbols are mapped to actual exceptions:

  'ActionController::RoutingError'             => :not_found,
  'AbstractController::ActionNotFound'         => :not_found,
  'ActiveRecord::RecordNotFound'               => :not_found,
  'ActiveRecord::StaleObjectError'             => :conflict,
  'ActiveRecord::RecordInvalid'                => :unprocessable_entity,
  'ActiveRecord::RecordNotSaved'               => :unprocessable_entity,
  'ActionController::MethodNotAllowed'         => :method_not_allowed,
  'ActionController::NotImplemented'           => :not_implemented,
  'ActionController::InvalidAuthenticityToken' => :unprocessable_entity

However the mappings of the 100 - 400 range are gone from Rails, probably because they are already present in Rack.



回答2:

Ruby on Rails uses Rack. The status codes are defined in Rack::Utils:

HTTP_STATUS_CODES = {
  100  => 'Continue',
  101  => 'Switching Protocols',
  102  => 'Processing',
  200  => 'OK',
  201  => 'Created',
  ...
}

Then those are used to create symbols (i.e. :switching_protocols):

SYMBOL_TO_STATUS_CODE = Hash[*HTTP_STATUS_CODES.map { |code, message|
  [message.downcase.gsub(/\s|-/, '_').to_sym, code]
}.flatten]

The whole code is browsable here.