将查询错误转换为 MySQLi 中的异常 [英] Turning query errors to Exceptions in MySQLi

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

问题描述

我试图将 MySQLi 查询错误转换为异常,但不能 - mysqli_sql_exception 只有在连接数据库失败时才会抛出.

I'm trying to turn MySQLi query errors to Exceptions, but couldn't - mysqli_sql_exception is thrown only if it failed to connect the DB.

我使用了 mysqli_report(MYSQLI_REPORT_STRICT) 和嵌入到自定义包装类中的程序 MySQLi 函数.

I used mysqli_report(MYSQLI_REPORT_STRICT) and procedural MySQLi functions embedded to custom wrapper class.

以前的代码:

public function mysqlQuery($SQL) {

    $this->Result = mysqli_query($this->DBlink, $SQL);

    if($this->Result === false)
        throw new MySQLiQueryException($SQL, mysqli_error($this->DBlink), mysqli_errno($this->DBlink));

    return $this->Result;

}

问题:查询失败时没有警告或异常是否正常,所以我必须检查mysqli_query()是否返回false?

Question: Is it normal no Warning, nor Exception are thrown when query fails so I have to check if mysqli_query() returned false?

推荐答案

前段时间我设法解决了这个问题.正如其他答案中指出的那样,

Some time ago I managed to sort this matter out. As it was pointed out in the other answer,

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

是告诉mysqli抛出异常的正确方法.

is a correct way to tell mysqli to throw exceptions.

只要确保不要将每个查询都包含在 try-catch 中.这是一个非常普遍的误解,即一旦开始使用异常,就应该开始向左和向右抛出尝试和捕获.恰恰相反,应谨慎使用 try-catch.虽然 99% 的错误不应该就地处理,而是由站点范围的错误处理程序处理.您可以从我关于 PHP 错误报告

Just make sure you don't wrap every query in a try-catch. This is a very common misconception that as soon as you started using exceptions you should start throwing tries and catches left and right. Quite contrary, try-catch should be used warily. While 99% of your errors shouldn't be handled in place, but rather by a site-wide error handler. You may read more on the topic from my article on PHP error reporting

这篇关于将查询错误转换为 MySQLi 中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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