简体   繁体   English

数据库模型异常,该如何处理?

[英]Exceptions in database model, how do I handle it?

I am creating a model for a small PHP application. 我正在为一个小型PHP应用程序创建模型。 This will utilize PDO to communicate with a MySQL-server. 这将利用PDO与MySQL服务器进行通信。 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? 或当我创建该对象时,“新模型”返回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. 完全取决于error_log函数的功能。

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(); 您可以通过throw()返回自定义异常;

It's really just your preference. 这实际上只是您的偏好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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