开发者

Getting access to :not_found, :internal_server_error etc. in Rails 3

开发者 https://www.devze.com 2023-02-22 13:40 出处:网络
It looks like ActionController::StatusCodes has been removed from Rails 3. I used synonyms for HTTP status codes such as

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-L开发者_JAVA百科ist-of-status-codes-and-their-symbols

Where can I find these in Rails 3?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消