Skip to content

[CodeQuality] Add NarrowPreviousExceptionCodeArgRector - #9052

Merged
TomasVotruba merged 3 commits into
mainfrom
remove-caught-exception-code
Nov 24, 2026
Merged

TomasVotruba merged 3 commits into
mainfrom
remove-caught-exception-code

Conversation

@TomasVotruba

@TomasVotruba TomasVotruba commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Follow up of #9014, as a standalone rule in the code-quality and named-args sets instead of a config option.

Removes the previous exception's code, when all 3 arguments are passed and the code comes from the same variable as previous:

 try {
     $someCode = 1;
 } catch (Throwable $throwable) {
-    throw new \RuntimeException('ups', $throwable->getCode(), $throwable);
+    throw new \RuntimeException('ups', previous: $throwable);
 }

Works with positional, named and mixed arguments. Skips explicit codes, other variables, and constructors where position 1/2 are not code/previous.

Change in ThrowWithPreviousExceptionRector

It no longer adds $e->getCode() when previous: is already passed as named argument. Otherwise both rules would revert each other in the code-quality set. Running both now converges to new X('msg', previous: $e).

Note: PHP does not inherit the code from previous exception, so getCode() of the new exception becomes 0. The original code is still available via getPrevious()->getCode().

Thanks @blancks for the original idea.

@TomasVotruba TomasVotruba changed the title [CodeQuality] Add RemovePreviousExceptionCodeRector [CodeQuality] Add NarrowPreviousExceptionCodeArgRector Nov 24, 2026
@TomasVotruba
TomasVotruba merged commit af652e0 into main Nov 24, 2026
51 checks passed
@TomasVotruba
TomasVotruba deleted the remove-caught-exception-code branch November 24, 2026 10:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants