Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write long exception statements avoiding rubocop line length error

I'm using a rescue statement exceeding the length of 120, because of which Rubocop shows offences. What should be the best way to write it?

Original statement:

 rescue ActiveResource::ResourceNotFound, ActiveResource::BadRequest, ActiveResource::TimeoutError, ArgumentError => e

Modified Statement:

 rescue ActiveResource::ResourceNotFound, ActiveResource::BadRequest, ActiveResource::TimeoutError,
    ArgumentError => e

But it doesn't look right and also not readable. What is the best way to write it?

like image 520
Ahmad hamza Avatar asked Nov 26 '25 13:11

Ahmad hamza


1 Answers

When I have a long list of errors to rescue, I generally handle it like this:

class MyClass < Object
  HandleTheseErrors = [
    ActiveResource::ResourceNotFound,
    ActiveResource::BadRequest,
    ActiveResource::TimeoutError,
    ArgumentError
  ]

  def do_something
    begin
      # do something error prone
    rescue *HandleTheseErrors => e
      puts e
    end
  end
end

The *HandleTheseErrors says, pass each of the elements of the HandleTheseErrors array as arguments to the rescue method.

like image 127
infused Avatar answered Nov 29 '25 15:11

infused



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!