php取出最后一条,PHP 得到某连接的最后一条错误信息

这篇博客讨论了在使用PostgreSQL时遇到的两种错误类型:普通错误和死锁。当发生普通错误时,应用应停止并显示错误信息给用户;而遇到死锁时,应用应重试交易。文章提供了一个PHP示例,展示如何通过错误消息中的模式来区分这两种错误,并相应地抛出PostgresException或DependencyException。示例代码包括一个数据库连接类和处理查询的函数,以及如何在前端捕获和处理这些异常。
摘要由CSDN通过智能技术生成

From a practical view there are two types of error messages when using transactions:

-"Normal" errors: in this case, the application should stop the current process and show an error message to the user.

-Deadlock errors. This shows that the deadlock detection process of PostgreSQL found a circle of dependency, and broke it by rolling back the transaction in one of the processes, which gets this error msg. In this case, the application should not stop, but repeat the transaction.

I found no discrete way to find out which case are we dealing with. This interface doesn't support error codes, so we have to search for patterns in the message text.

Here is an example for PostgreSQL database connection class. It throws a PostgresException on "normal" errors, and DependencyException in the case of a broken deadlock, when we have to repeat the transaction.

postgres.php:

function__construct($msg) {parent::__construct($msg); }

}

classDependencyExceptionextendsPostgresException{

function__construct() {parent::__construct("deadlock"); }

}

classpg{

public static$connection;

private static functionconnect() {self::$connection= @pg_connect("dbname=foodb user=foouser password=foopasswd");

if (self::$connection===FALSE) {

throw(newPostgresException("Can't connect to database server."));

}

}

public static functionquery($sql) {

if (!isset(self::$connection)) {self::connect();

}$result= @pg_query(self::$connection,$sql);

if ($result===FALSE) {$error=pg_last_error(self::$connection);

if (stripos($error,"deadlock detected") !==false) throw(newDependencyException());

throw(newPostgresException($error.": ".$sql));

}$out= array();

while ( ($d=pg_fetch_assoc($result)) !==FALSE) {$out[] =$d;

}

return$out;

}

}?>

It should be used in this way:

test.php:

do {$repeat=false;

try {pg::query("begin");

...$result=pg::query("SELECT * FROM public.kitten");

...pg::query("commit");

}

catch (DependencyException $e) {pg::query("rollback");$repeat=true;

}

} while ($repeat);?>

The normal errors should be caught at the frontend.

Tamas

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值