库MySQLi错误处理? [英] MySQLi Error Handling?

查看:119
本文介绍了库MySQLi错误处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用面向对象的程序MySQLi的MySQL后,我有一个问题。

I started using OO-MySQLi after procedural MySQL and I have a problem.

在生产环境中我的系统显示所有错误作为一个自定义页面。
库MySQLi错误是一个错误也和我想赶上他们,但在文档中描述只有一个办法做到这一点:

In production environment my system displays all errors as a custom page. MySQLi errors is an "error" too and I want catch them, but in documentation described only one way to do this:

if (!$mysqli->query("SET a=1")) {
    exit('An error occurred: ' . $mysqli->error);
}

(只是例子)。
这是一个非常不错的方法,因为在我的系统我做很多事情发生错误时,如日志,称事件等。

(just for example). This is a very bad way, because in my system I'm doing many things when error occurred, like logging, calling events, etc.

当然,我可以扩展的mysqli类,例如:

Of course, I can extend mysqli class, for example:

class myMysqli {
    public function __construct(/* ... */)
    {
        parent::__construct(/* ... */);
    }

    public function query(/* .. */)
    {
        parent::query(/* ... */);

        if($this->errno !== 0)
        {
            // An error occurred
        }
    }
}
$mysqli = new myMysqli(/* ... */);
$mysqli->query(/* ... */);

但这种方式,我需要延长几乎全部方法可能发生错误。
此外,库MySQLi提供prepared语句(mysqli_stmt类),有它自己的错误!

But this way I need to extend almost ALL methods where error can occur. Moreover, MySQLi provides prepared statements (mysqli_stmt class) that has its own errors!

你能知道一个更好的方式来处理MySQLi的错误?
谢谢你在前进。

Can you know a better way to handle MySQLi errors? Thank you in advance.

添加

关于例外:
难道我理解正确,与例外,我需要做这样的事情:

About exceptions: Do I understand correctly that with exceptions I need do something like this:

try {
    $mysqli->query(/* ... */);
} catch (Exception $e) {
    // An error occurred
}

但是,这是类似于

But this is similar to

if(!$mysqli->query(/* ... */))
{
    // An error occured
} 

有什么区别?

推荐答案

我用的try ... catch方法,像这样...

I use the try...catch method like this...

try {
    // get result of record from 'id'
    $query = "SELECT * FROM models WHERE id =$id";
    $result = $mysqli->query($query);

    if (!$result) {
        throw new Exception($mysqli->error());      
    } 
    $row = $result->fetch_array(); 
 }
 catch (Exception $e)  
 {
     echo "We are currently experiencing issues. Please try again later.";
     echo $e->getMessage();
 } 
 finally
 {
      $result->free();
 }

这是否帮助呢?

您使用'尝试'来测试一个条件,如果返回true(!$结果)抛出一个异常。并使用'抓'捕捉一切可能只是发生!

You use 'try' to test a condition and throw an exception if it returns true (!$result). And use 'catch' to catch everything else that might just happen!

这篇关于库MySQLi错误处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆