简体   繁体   中英

Exceptions in database model, how do I handle it?

I am creating a model for a small PHP application. This will utilize PDO to communicate with a MySQL-server. I have understood that the recommended error mode is the one which throws exceptions, as this allows for graceful error handling. But I don't understand how I should handle these exceptions?

Technically, it is easy, but let me give you an example:

class Model()
{
    private $host = "localhost", 
            $user = "",
            $pass = "",
            $DBH;


    function __construct()
    {
        try
        { 
            $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

            $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        }  
        catch(PDOException $e)
        {  
            error_log($e->getMessage());
        }
    }
}

If I create an object Model in my controller, and it fails, I have no way of handling this in my controller, right? Or what happens when I create that object, "new Model" returns false?

Excuse me for being a newbie, but I want to be able to handle any exceptions also from other functions in the model. How should I go about this? I need to be able to know if something went wrong in my controller and be able to do the appropriate thing there.

If you want your controller to catch the exception as well, you can always rethrow it after logging.

class Model()
{
    ...

    function __construct()
    {
        try
        { 
            ...
        }  
        catch(PDOException $e)
        {  
            error_log($e->getMessage());
            throw $e;
        }
    }
}

Depends entirely on what the error_log function does.

You can return the exception. You can simply die after logging the error (presumably if your application can't hit the DB then theres no graceful recovery). You can return a custom exception via throw();

It's really just your preference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM