Assuming the following example code:
/**
* @method bool someMethod()
*/
class MyClass
{
/**
* @throws MyClassException
*/
public function __call($method, $args)
{
if ($this->someCheck()) {
throw new MyClassException();
}
}
}
//...
try {
(new MyClass())->someMethod();
} catch (MyClassException $e) { // Reported by PHPStorm as not thrown!
// of course the exception is properly caught
}
How can I make IDE detect exceptions thrown by a methods declared with @method
docblock? Wonder if this is even possible to do, if not - what are my alternatives?
It seems like @throws
declared in magic methods are totally ignored in cases like this. Of course I could disable inspections but this isn't clean solution for me...
It says it was possible for some time (some 2018.1.x versions if I'm reading the ticket correctly) but then it was rolled back in 2018.1.3 "due to usability concerns".
I agree with that -- not everyone will be happy to see unhandled exception warnings for every magic method call (e.g. Laravel uses that a lot) -- simply because not every magical method can throw exceptions.
Anyway: https://youtrack.jetbrains.com/issue/WI-39284 -- watch this ticket (star/vote/comment) to get notified on any progress.
You can document exceptions for magic methods in this way:
/**
* MyClass summary.
*
* @method bool someMethod() {
* @throws MyClassException
* }
*/
class MyClass {
// ...
}
This syntax is part of PSR-5 draft. Standard is still not accepted, but it seems to work pretty well in PhpStorm.