Store response HTTP status code after exception in Rails
<p>I'm developing a REST web service in Ruby on Rails.</p>

<p>After each request I would like to store in the database the response HTTP status code even in presence of some exception. How can I do that?</p>

<p>I have done these two attempts without success:</p>

<ul>
<li><p>after_filter in application controller</p>

<pre><code>class Api::ApiController &lt; ActionController::Base
    before_action :set_current_rest_request
    after_filter :finalize_current_rest_request
    private
    def set_current_rest_request
        @current_rest_request = RestRequest.new
        @current_rest_request.request_at = DateTime.now
        @current_rest_request.save
    end
    def finalize_current_rest_request
        @current_rest_request.answer_at = DateTime.now
        @current_rest_request.http_status_code = response.status
        @current_rest_request.save
    end
end
</code></pre>

<p>Doesn't work because finalize_current_rest_request is not called in case of exceptions</p></li>
<li><p>rescue_from in application controller</p>

<pre><code>class Api::ApiController &lt; ActionController::Base
    before_action :set_current_rest_request
    after_filter :finalize_current_rest_request
    rescue_from Exception, :with =&gt; :handle_exception
    private
    def set_current_rest_request
        @current_rest_request = RestRequest.new
        @current_rest_request.request_at = DateTime.now
        @current_rest_request.save
    end
    def finalize_current_rest_request
        @current_rest_request.answer_at = DateTime.now
        @current_rest_request.http_status_code = response.status
        @current_rest_request.save
    end
    def handle_exception(exception)
        finalize_current_rest_request
        raise exception
    end
end
</code></pre>

<p>Doesn't work because response.status is still 200 when I call finalize_current_rest_request inside handle_exception, before the raise of the exception</p></li>
</ul>