4

Here is the 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 try to catch an exception if by some accident the action of the controller with the defined name is not implemented or if the name is defined wrongly.

But instead of catching exception I get Fatal Error in Apache's error log:

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

If I try to call an undefined method inside the existing (defined and callable) action of the controller, I also can't catch the aforementioned exception - the Fatal Error occurs instead:

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

Replacing the "\BadMethodCallException" by the "\Exception" has no effect: I'm keeping get the Fatal Errors.

Putting the "try-catch" block inside the every action of the controller is not the acceptable solution for me.

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

I'm running PHP 5.3.8.

user1764823
  • 425
  • 2
  • 8
  • 16

1 Answers1

3

Catch blocks can only catch thrown exceptions, not errors. Call to undefined method is an error and you will need to test for this and throw an exception yourself. Please see this for differences between exceptions and errors.

You can test whether a method exists by doing something like this:

if( !method_exists('app\Controller', 'testingAction') ) {
    throw new \BadMethodCallException();
}
Community
  • 1
  • 1
Nathan Kot
  • 2,392
  • 1
  • 21
  • 31
  • If so, what is the special meaning of the PHP's native "BadMethodCallException" class? Can it be thrown only by this straightforward way? – user1764823 Nov 21 '12 at 13:49
  • 1
    Yep, its in PHP's SPL and works similar to `\Exception`, just allows you to be more specific with your exceptions without having to define the class yourself, [take a look at this](http://codeutopia.net/blog/2011/05/06/how-to-use-built-in-spl-exception-classes-for-better-error-handling/) – Nathan Kot Nov 21 '12 at 13:54
  • Note that you can set an error handler which converts PHP errors to exceptions. Here's an example on [converting errors to exceptions](https://github.com/laravel/framework/blob/53fb3c1f0db3fdbc06155ea405f12fcc4379020c/src/Illuminate/Exception/Handler.php#L95) – fideloper Jan 18 '14 at 01:47