Reputation: 1573
I'm working on a simple MVC framework and I am using autoloading of classes and I want to use class_eixists()
to check if the controller name parsed from the URI actually exists and respond appropriately. I started with
$controller = "\\namespace\\controller";
if(class_exists($controller))
$this->controllerObject = new $controller();
else
// react appropriately
This ended up throwing an uncaught logic exception if the class didn't exists. If my google-fu hasn't failed me then this is a normal event when using autoloading and the class_exists()
function. I figured no big deal and wrapped it in a try catch but I'm still getting the uncaught exception and I can't see what I'm doing wrong.
try {
if (class_exists($controller)) {
$this->controllerObject = new $controller(array_slice($parsedURI, 1));
echo "controller is $controller<br />";
}
} catch (LogicException $e) {
$e->getMessage();
} catch (Exception $e) {
$e->getMessage();
}
The error output is below. Line 57 is the line with (if (class_exists($controller))
). I changed up the actual paths manually because the system administrator is paranoid about any internal info being made public.
Fatal error: Uncaught exception 'LogicException' with message 'Class
Controller\Gibberish could not be loaded' in some/path/private/webroot/assets/route.php:57 Stack trace: #0 [internal function]:
spl_autoload('Controller\Gibb...') #1
some/path/private/app/webroot/assets/route.php(57): class_exists('\Controller\Gib...')
#2 some/path/private/app/webroot/index.php(32): Assets\Route-
>__construct('/add/webroot/...') #3 {main} thrown in
some/path/private/app/webroot/assets/route.php on line 57
Upvotes: 2
Views: 1353
Reputation: 1573
Almost 2 hours of searching for an answer before I post and less than half of one afterward before I find the answer. The reason I couldn't catch the exception is because the logic is inside a method of a class that is inside a namespace. In order to catch the LogicException
it has to be prefixed with a \
to specify the global namespace.
try {
if (class_exists($controller)) {
$this->controllerObject = new $controller(array_slice($parsedURI, 1));
echo "controller is $controller<br />";
}
} catch (\LogicException $e) {
$e->getMessage();
}
I found two other questions with an identical issue:
PhpMailer throwing Fatal Exceptions
Facebook PHP SDK Throwing an Uncatchable OAuthException
Upvotes: 3