I have small/mid sized PHP application built for practicing OOP and MVC skills. I have init/bootstrap file which calls Router who calls Controller -> Service Layer -> Repository (Database) and then sends back variables to View Layer (all dependencies handled with DiC/IOC).
I created abstract class BaseException that extends Core Exception class. Then I have different Exception classes - DatabaseException, FileException etc.
Example triggering Exception: In Database Layer I try to fetch data from database, if it fails it throws new DatabaseException.
Example 2: In classes which I handle file include, save, delete - if error occurs it throws new FileException.
Where to put try catch code, in init/bootstrap file or maybe in BaseController ? But what if Controller fails and it throws some kind of ControllerException.
In my opinion it might look like this (init.php file):
try {
// create new router
$router = $container->get('Router');
$router->import'Config/routes.php');
// run the router
$router->route();
// load controller
$dispatcher = $container->get('Dispatcher');
$dispatcher->load();
} catch (DatabaseException $e) {
echo "Database error!";
$log->log('Database error', $e->getMessage());
} catch (FileException $e) {
echo "File error!";
$log->log('File error', $e->getMessage());
} catch (Exception $e) { // default
echo "Some exceptional error!";
$log->log('Default exception', $e->getMessage());
}
One more question, how to log these exceptions (errors), like example above or should I inject Log class in BaseException and handle logging there ?