Skip to content

Commit

Permalink
[Fix rubocop#10622] Fix a false positive for Style/RaiseArgs
Browse files Browse the repository at this point in the history
Fixes rubocop#10622.

This PR fixes a false positive for `Style/RaiseArgs` when
error type class constructor with keyword arguments and message argument.

The signature of `raise` is below.

```ruby
raise
raise(string, cause: $!)
raise(exception [, string [, array]], cause: $!)
```

https://ruby-doc.org/core-3.1.0/Kernel.html#method-i-raise

So rubocop#10622 would be a false positive because `raise MyError.new(data: 'mydata'), 'message'` and
`raise MyError.new('message', data: 'mydata')` are incompatible.
  • Loading branch information
koic committed May 11, 2022
1 parent fbe6b7b commit 83cd538
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/fix_a_false_positive_for_style_raise_args.md
@@ -0,0 +1 @@
* [#10622](https://github.com/rubocop/rubocop/issues/10622): Fix a false positive for `Style/RaiseArgs` when error type class constructor with keyword arguments and message argument. ([@koic][])
3 changes: 3 additions & 0 deletions lib/rubocop/cop/style/raise_args.rb
Expand Up @@ -91,6 +91,9 @@ def correction_exploded_to_compact(node)

def check_compact(node)
if node.arguments.size > 1
exception = node.first_argument
return if exception.send_type? && exception.first_argument&.hash_type?

add_offense(node, message: format(COMPACT_MSG, method: node.method_name)) do |corrector|
replacement = correction_exploded_to_compact(node)

Expand Down
4 changes: 4 additions & 0 deletions spec/rubocop/cop/style/raise_args_spec.rb
Expand Up @@ -145,6 +145,10 @@
it 'accepts a raise with an exception argument' do
expect_no_offenses('raise Ex.new(msg)')
end

it 'accepts exception constructor with keyword arguments and message argument' do
expect_no_offenses('raise MyKwArgError.new(a: 1, b: 2), message')
end
end

context 'when enforced style is exploded' do
Expand Down

0 comments on commit 83cd538

Please sign in to comment.