使用Exceptions控制应用程序流

时间:2015-04-24 21:45:15

标签: php oop exception

我目前正在用PHP编写一个Web应用程序,并决定使用异常(呃!)。

我找不到在所有函数中放置try和catch块是否会被视为错误代码的答案。

我目前正在使用Exceptions来处理数据库错误(应用程序错误是通过一个简单的函数处理的,它只是将它们添加到数组中然后显示给用户)。 try块放在需要数据库连接的所有函数上。

有问题的代码是:

public function db_conn_verify()
{
    if(!isset($this->_mysqli)){
        throw new Exception("Network Error: Database connection could not be established.");
    } else {
        return Null;
    }
}

使用此代码的示例函数:

public function get_users() {
    try {
        $this->db_conn_verify();

        //Rest of function code

        return True;

    } Catch(Exception $e) {
        Core::system_error('function get_users()', $e->getMessage());
        return False;
    }
}

扩展Exception类然后使用新的Exception类来处理应用程序错误会更好吗?

由于

1 个答案:

答案 0 :(得分:0)

我建议你使用这样的东西:

public function get_users() {

        try {
            if( !isset($this->_mysqli) ) {
                 throw new Exception("Network Error: Database connection could not be established.");
            }

            //Rest of function code

        } Catch(Exception $e) {
            Core::system_error('function get_users()', $e->getMessage());
        }
}

我更喜欢使用我的Exception代码,但它是相同的。对于exdending异常,您可以看到PHP documentation到示例#5

编辑:要立即使用try-catch数据库连接错误,您可以尝试这样做:

try{
    $mysqli = new mysqli("localhost", "user", "password", "database");
    if ($mysqli->connect_errno) {
        throw new Exception("Network Error: Database connection could not be established.");
    }
} Catch(Exception $e) {
  Core::system_error('function get_users()', $e->getMessage());
}