Error Identifier: catch.notThrowable
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
class NotAnException
{
}
try {
// ...
} catch (NotAnException $e) {
// ...
}
Why is it reported? #
PHP only allows catching classes that implement the Throwable interface. All exception classes must either extend \Exception (which implements Throwable) or directly implement Throwable. Attempting to catch a class that does not implement Throwable will result in a fatal error.
In the example above, NotAnException is a regular class that does not extend \Exception or implement \Throwable, so it cannot be used in a catch block.
How to fix it #
Make the class extend \Exception or one of its subclasses:
<?php declare(strict_types = 1);
-class NotAnException
+class NotAnException extends \RuntimeException
{
}
try {
// ...
} catch (NotAnException $e) {
// ...
}
Alternatively, if this class should not be an exception, catch the correct exception class instead:
<?php declare(strict_types = 1);
try {
// ...
-} catch (NotAnException $e) {
+} catch (\RuntimeException $e) {
// ...
}
How to ignore this error #
You can use the identifier catch.notThrowable to ignore this error using a comment:
// @phpstan-ignore catch.notThrowable
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: catch.notThrowable
Rules that report this error #
- PHPStan\Rules\Exceptions\CaughtExceptionExistenceRule [1]