Cannot catch BadMethodCallException

Here is part of my code:

// ... code ... $action = self::defineAction( $request->getPath() ); try { $response = Controller::$action( $request ); } catch( \BadMethodCallException $exception ) { Logger::logError( $exception ); $response = new NotFoundResponse(); } // ... code ... 

I am trying to catch an exception if, for some reason, the action of a controller with a specific name is not implemented or if the name is not defined correctly.

But instead of throwing an exception, I get Fatal Error in the Apache error log:

 PHP Fatal error: Call to undefined method app\\Controller::testingAction() ... 

If I try to call the undefined method inside an existing (defined and called) controller action, I also cannot catch the above exception - Fatal Error occurs instead:

 PHP Fatal error: Call to undefined method app\\SomeClass::someUndefinedMethod() in /********/Controller.php on line *** ... 

Replacing "\ BadMethodCallException" with "\ Exception" does not affect: I keep Fatal Errors.

Putting a try-catch block inside every controller action is not an acceptable solution for me.

Why can't an exception be caught this way? How can I solve this problem?

I am running PHP 5.3.8.

+4
source share
1 answer

Blocking blocks can only throw thrown exceptions, not errors. Call to undefined method is a mistake, and you will need to test this and throw an exception yourself. Refer to this question for differences between exceptions and errors.

You can check if a method exists by doing something like this:

 if( !method_exists('app\Controller', 'testingAction') ) { throw new \BadMethodCallException(); } 
+3
source

Source: https://habr.com/ru/post/1447490/


All Articles