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

时光总嘲笑我的痴心妄想 提交于 2019-12-06 11:58:16

问题


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.



来源:https://stackoverflow.com/questions/5542339/getting-access-to-not-found-internal-server-error-etc-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!