简体   繁体   中英

Rails - Rubocop - Begin + Rescue syntax

I have the following code:

  def payload
    begin
      @payload ||= Warden::JWTAuth::TokenDecoder.new.call(token)
    rescue JWT::ExpiredSignature => e
      Rollbar.warning(e)
    end
  end

From brief reading of a few blogs I'm supposed to be using begin rescue and end to handle the error as I'm doing above, however I'm getting a redundant 'begin' rubocop warning.

Is begin only used when specifying a bit of code that may cause an error within a larger block? And is it therefore redundant here?

Thanks in advance

EDIT: And if I don't need it, is it written as

  def payload
    @payload ||= Warden::JWTAuth::TokenDecoder.new.call(token)
  rescue JWT::ExpiredSignature => e
    Rollbar.warning(e)
  end

?

Do this when the begin would be the first thing in your method

def payload
  @payload ||= Warden::JWTAuth::TokenDecoder.new.call(token)
rescue JWT::ExpiredSignature => e
  Rollbar.warning(e)
end

Method bodies, block bodies, and lambda bodies are implicit exception blocks. You don't need to wrap the entire code of a method body, block body, or lambda body in a begin / rescue / else / ensure / end exception block, since it is already implicitly one. So, whenever you have something like

def foo
  begin
  rescue
  end
end

or

foo do
  begin
  rescue
  end
end

or

-> do
  begin
  rescue
  end
end

you can replace it with just

def foo
rescue
end

or the equivalent for blocks and lambdas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM