How to handle malformed json for a route with 'defaults: {format: :json}'?

Oddamati

New Member
#1
I have a url which is supposed to accept only json:
Mã:
put "/my_url" => "my_controller#my_actio", defaults: {format: :json}
When I send malformed json to it, it doesn't make to an "action" at all and instead it throws an exception somewhere in Rails and thus my app ends up returning the error 500. Namely, that's an unhandaled exception.

How can I fix that?
 

Admin

Administrator
Thành viên BQT
#2
For you to raise those exception and return 422.

You'll have to create a file under app/middleware, let's call it json_parse_errors.rb

Mã:
# app/middleware/json_parse_errors.rb
class JsonParseErrors
  def initialize(app)
    @app = app
  end

  def call(env)
    begin
      @app.call(env)
    rescue ActionDispatch::ParamsParser::ParseError => error
      if env['HTTP_ACCEPT'] =~ /application\/json/
        error_output = "There was a problem in the JSON you submitted: #{error}"
        return [
          400, { "Content-Type" => "application/json" },
          [ { status: 422, error: error_output }.to_json ]
        ]
      else
        raise error
      end
    end
  end
end
In your application.rb, add the following line
Mã:
config.middleware.use JsonParseErrors
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top