Where to look for exceptions in a PHP MVC application?

I have a small / medium PHP application built for practical OOP and MVC skills. I have an init / bootstrap file that calls a Router that calls ControllerService LevelRepository (Database) , and then sends the variables back to the View Layer (all dependencies are processed using DiC / IOC).

I created an abstract BaseException class that extends the Core Exception class . Then I have different exception classes - DatabaseException, FileException, etc.

Example trigger Exception: In a database layer I try to retrieve data from a database; if it fails, it throws a new DatabaseException.

Example 2: In the classes in which I process the file, there is, save, delete - when an error occurs, it throws a new FileException.

Where to put the try catch code in the init / bootstrap file or, possibly, in BaseController? But what happens if Controller fails and it throws some sort 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 register these exceptions (errors), for example, the above example, or should I introduce a log class in BaseException and handle it there?

+4
1

php, try/catch , .

( MVC) , . , , .

, , , , Laravel ( ).

set_exception_handler() PHP.

, docs:

set_exception_handler(function($exception){

    //you could write in a log file here for example...
    echo "Uncaught exception: " , $exception->getMessage(), "\n";

});
+1

All Articles