1

I'm rescuing an unauthorized exception, and want to render an alert within this rescue block. Since this is in my application controller, this rescue could be hit in multiple formats, so I need a respond_to block.

If I do this without a respond_to, everything works fine. The status is set to 401, and I see the proper exception message flashed.

render :json => exception.message, :status => 401

However, if I do the same thing inside a repond_to block, nothing works. Status doesn't get set, and the exception message doesn't get rendered.

respond_to do |format|
  format.json { render :json => exception.message, :status => 401 }
end

What could be the problem here? I've looked through a ton of examples, and this seems like it should work, but the status and message seem to be ignored.

123
  • 8,733
  • 14
  • 57
  • 99
  • In the 1st variant you render response to all the requests to controller action despite what their format is. Second variant defines response only for json format requests, e.g. `/example/new.json`. If you make a request to your action like this `/example/new` it will fallback to html format for which you don't define any status and message. See this question and answer for more details: http://stackoverflow.com/questions/9492362/rails-how-does-the-respond-to-block-work – Slava.K Feb 22 '17 at 15:47

1 Answers1

0

Besides you are rendering a json with

render :json => exception.message, :status => 401

You are answering to HTML requests... So if you need to render it on browsers, you need to handle all format yourself...

respond_to do |format|
  format.json { ... }
  format.html { ... }
end
cefigueiredo
  • 738
  • 3
  • 12
  • I mean... the way you are asking, I guess you only have problems testing it on your browser... if not hitting the endpoint with the `.json` format at the end... like `/controller/action.json` – cefigueiredo Feb 22 '17 at 21:59