ruby-on-railsrubyrescue

How to rescue from a specific error (Ruby on Rails)


I have a specific error I want to rescue from;

The error grabbed from the console is...

JSON::ParserError: 751: unexpected token at ''

begin
    #do stuff
rescue
    if error is <JSON::ParserError: 751: unexpected token at ''>
         #do stuff
         next
    end
end

Solution

  • You can catch different errors and do the same action on them or do different actions. The syntax is the following.

    Imagine you want to do different actions for different errors:

    begin
      # Do something
    rescue JSON::ParseError
      # Do something when the error is ParseError
    rescue JSON::NestingError, JSON::UnparserError
      # Do something when the error is NestingError or UnparserError
    rescue JSON::JSONError => e
      # Do something when the error is JSONError
      # Use the error from this variable `e'
    rescue # same as rescue StandardError
      # Do something on other errors
    end
    

    If you are going to place all the code in the function inside a begin rescue end block, then you can ommit the begin end words, so instead of writing:

    def my_func
      begin
        # do someting
      rescue JSON::ParseError
        # handle error
      end
    end
    

    You may write

    def my_func
      # do something
    rescue JSON::ParseError
      # handle error
    end
    

    Remember to never rescue from Exception. I know my answer may be a little too broad for your question but I hope it helps you and other people in similar doubts.