Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Handling Invalid JSON errors in rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 418
    Comment on it

    Handling Invalid JSON Error in Rails 

    Hi Friends,
    Sometimes by mistake, when we send an incorrect JSON to server, the server is not able of handle the improper JSON so it throws an error, and the client doesn't get any proper error message. Today I am going to tell you how we can handle that.
    If you try to handle the json parse errors inside controller, you won't be able to do that because, parsing of the JSON is done in middleware ActionDispatch::ParamsParser, that throws an exception before the controller comes into picture. So we need to handle it, before it reaches to controller, In Rails we can do this using the rake middleware. For handling the json parse error you need to create a middleware file like this:

     

     

    ## app/middleware/handle_incorrect_json.rb
    
    class HandleIncorrectJson
      def initialize(app)
        @app = app
      end
    
      def call(env)
        begin
          @app.call(env)
        rescue ActionDispatch::ParamsParser::ParseError => e
          if env['HTTP_ACCEPT'] =~ /application\/json/
            return [
              400, 
              { "Content-Type" => "application/json" },
              [ { status: 400, error_message: "The JSON you sent has this error:
              	#{e}" }.to_json 
              ]
            ]
          else
            raise e
          end
        end
      end
    end
    

    Now at last you need to insert the middleware before the ActionDispatch::ParamsParser inside config/application.rb

    ## config/application.rb
    module AppName
      class Application < Rails::Application
     		...........................
     		...........................
        config.middleware.insert_before ActionDispatch::ParamsParser, "HandleIncorrectJson"
        ...........................
        ...........................
      end
    end
    

    Now from now your application will deal all kind of improper json formatting errors in your way. Hope you liked reading this.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: