Martin Sojka
Martin Sojka

Reputation: 533

DoubleRenderError in Rails 4.1 when rescuing from InvalidCrossOriginRequest

I've upgraded to Rails 4.1.0 today. Cross-site request forgery (CSRF) protection now covers GET requests with JavaScript responses, too.

I have a few remote GET links in the app that are hit by the bots and are now throwing ActionController::InvalidCrossOriginRequest exception.

So I added another rescue_from line to application_controller:

rescue_from ActionController::InvalidCrossOriginRequest, with: :render_400

Here's the render_400 method:

def render_400
    render(nothing: true, status: 400) and return
end

I'm still getting AbstractController::DoubleRenderError even though I added and return as you can see above.

It happens only with the ActionController::InvalidCrossOriginRequest exception. Others like e.g. ActionController::BadRequest and not resulting in AbstractController::DoubleRenderError.

Upvotes: 6

Views: 1437

Answers (1)

Thomas Klemm
Thomas Klemm

Reputation: 10856

The underlying reason is that some part of the response_body is assigned before the error is triggered.

You could try clearing the response body before calling render in the exception handler.

def render_400
  # Clear the previous response body to avoid a DoubleRenderError
  # when redirecting or rendering another view
  self.response_body = nil

  render(nothing: true, status: 400)
end

Upvotes: 8

Related Questions