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

那年仲夏 提交于 2019-12-04 15:17:48

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.

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.

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