Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to Rescue from ActionDispatch::ParamsParser::ParseError in Rails 4
    primarykey
    data
    text
    <p>Rails 4 adds an exception <strong>ActionDispatch::ParamsParser::ParseError</strong> exception but since its in the middleware stack it appears it can't be rescued in the normal controller environment. In a json API application I want respond with a standard error format.</p> <p>This <a href="https://gist.github.com/elarkin/4709748">gist</a> shows a strategy for inserting middleware to intercept and respond. Following this pattern I have:</p> <p><strong>application.rb:</strong></p> <pre><code>module Traphos class Application &lt; Rails::Application .... config.middleware.insert_before ActionDispatch::ParamsParser, "JSONParseError" end end </code></pre> <p><strong>And the middleware is:</strong></p> <pre><code>class JSONParseError def initialize(app) @app = app end def call(env) begin @app.call(env) rescue ActionDispatch::ParamsParser::ParseError =&gt; e [422, {}, ['Parse Error']] end end end </code></pre> <p>If I run my test without the middleware I get (spec):</p> <pre><code>Failures: 1) Photo update attributes with non-parseable json Failure/Error: patch update_url, {:description =&gt; description}, "CONTENT_TYPE" =&gt; content_type, "HTTP_ACCEPT" =&gt; accepts, "HTTP_AUTHORIZATION" =&gt; @auth ActionDispatch::ParamsParser::ParseError: 399: unexpected token at 'description=Test+New+Description]' </code></pre> <p>Which is exactly what I would expect (ParseError that I can't rescue_from).</p> <p>Now with the only change to add in the middleware above:</p> <pre><code> 2) Photo update attributes with non-parseable json Failure/Error: response.status.should eql(422) expected: 422 got: 200 </code></pre> <p>And the log shows that the standard controller action is being executed and returning a normal response (although since it didn't receive any parameters it didn't update anything).</p> <p>My questions:</p> <ol> <li><p>How can rescue from ParseError and return a custom response. Feels like I'm on the right track but not quite there.</p></li> <li><p>I can't work out why, when the exception is raised and rescued, that the controller action still proceeds.</p></li> </ol> <p>Help much appreciated, --Kip</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload