Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to catch exception in PHP MVC application?

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 ?

like image 936
fsasvari Avatar asked Nov 10 '22 09:11

fsasvari


1 Answers

Edit:

In Laravel newer versions, the application errors are handled in App\Exceptions\Handler class.

Original answer:

As in plain php, you can implement try/catches everywhere you might need.

In my projects (as a MVC framework user), I generally handle exceptions in my controllers methods, as they have the duty to handle processes in an application. But if needed, I would implement it in a middleware or even in a model if i want to.

In your case, it seems like you want to let your framework handle the exception before outputing it to the user interface, as Laravel (also many others) does.

You may accomplish this with set_exception_handler() function from PHP.

Here is an example based on the docs example:

set_exception_handler(function($exception){

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

});
like image 194
CarlosCarucce Avatar answered Nov 14 '22 23:11

CarlosCarucce