Getting HTTP response code from a controller

Hi there, how would I get the HTTP response code (200 OK, 500, etc…)
from a controller after a request have been ‘served’?

Thanks

I was able to get the response status after_filter by doing
response.headers[“Status”], but it only displays the 200 and 302
codes. Any ideas how I get get the others (404, 500, etc…) as well?

Thanks

Mark wrote:

Hi there, how would I get the HTTP response code (200 OK, 500, etc…)
from a controller after a request have been ‘served’?

Thanks

You’ll have to hook it somewhere else (eg, in Mongrel or a monkey/
mixin patch to ActionController::Base). Your controller won’t be
consulted in the case of a 404 or 500 error. Those are usually
generated from exceptions.

Is there a reason you need to know about these status codes in your
controller?

Eden Li,

I see what you mean. The reason why I need those status codes is for a
personal project that I’m doing and I need to store those codes in the
DB as-they-happen.

Could you give me a starting point for the monkey/mixin patch?

Thanks

Eden Li wrote:

You’ll have to hook it somewhere else (eg, in Mongrel or a monkey/
mixin patch to ActionController::Base). Your controller won’t be
consulted in the case of a 404 or 500 error. Those are usually
generated from exceptions.

Is there a reason you need to know about these status codes in your
controller?

Cool, I could have a use for that as well. Let me know if you guys
figure it out. In the meantime I’ll try to do it too.


Thiago J.
acts_as_solr => http://acts-as-solr.rubyforge.org
Sitealizer Web Stats => http://sitealizer.rubyforge.org

Here’s a first stab…

lib/final_response.rb

module FinalResponse
def self.included(base)
base.class_eval do
alias_method :process_without_final_response, :process
alias_method :process, :process_with_final_response
end
end

def process_with_final_response(*args)
process_without_final_response(*args)
ensure
final_response if respond_to?(:final_response)
end
end

app/controllers/my_controller.rb

class MyController < ActionController::Base
include FinalResponse
def final_response
logger.info(“status = #{headers[‘Status’]}”)
end

def action
raise
end
end

Your final_response method won’t have access to the session, but
you’ll still be OK to access models.

There’s probably a better way to do this, but this should work…