No commit activity in last 3 years
No release in over 3 years
This custom Cop forbids swallowing exception. See OWASP article. https://www.owasp.org/index.php/Exception_handling_techniques#Swallowing_Exceptions
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.13
~> 10.0
~> 3.0

Runtime

~> 0.43
 Project Readme

rubocop-swallow-exception

This is mmj's custom Cop that forbids swallowing exception. See OWASP article to understand why this Cop is required.

Installation

Add this line to your application's Gemfile:

gem 'rubocop-swallow-exception'

And then execute:

$ bundle

Or install it yourself as:

$ gem install rubocop-swallow-exception

Usage

Just add require option when you run rubocop.

$ rubocop --require rubocop-swallow-exception

example using in RubyMine

Specification

The Cop searches rescue body that does not contain raise statement in top level nor Raven.capture_exception (Sentry client) calling

See spec file below in detail.

it 'offense: rescue body is empty' do
  expect_offense(<<~RUBY)
    def bad_method
      p :hello
    rescue => e
    ^^^^^^^^^^^ swallow exception found
      # do nothing
    end
  RUBY
end

it 'ok: raise new exception without any condition' do
  expect_no_offenses(<<~RUBY)
    def bad_method
      p :hello
    rescue => e
      log.error 'error occured'
      log.error e.backtrace.join("\n")
      raise e
    end
  RUBY
end

it 'ok: call Raven.capture_exception' do
  expect_no_offenses(<<~RUBY)
    def bad_method
      p :hello
    rescue => e
      Raven.capture_exception(e)
    end
  RUBY
end

it 'offense: logging only' do
  expect_offense(<<~RUBY)
    def bad_method
      p :hello
    rescue => e
    ^^^^^^^^^^^ swallow exception found
      log.error 'error occured'
      log.error e.backtrace.join("\n")
    end
  RUBY
end

it 'offense: just return value' do
  expect_offense(<<~RUBY)
    def verify_token(env)
      token = BEARER_TOKEN_REGEX.match(env['HTTP_AUTHORIZATION'])[1]
    rescue ::JWT::VerificationError => error
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ swallow exception found
      3
    end
  RUBY
end

it 'offense: only logging with some method, and just return value' do
  expect_offense(<<~RUBY)
    def verify_token(env)
      token = BEARER_TOKEN_REGEX.match(env['HTTP_AUTHORIZATION'])[1]
    rescue ::JWT::VerificationError => error
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ swallow exception found
      write_log(error)
      return_error('token_signature_verification_failed')
    end
  RUBY
end

License

The gem is available as open source under the terms of the MIT License.