fatfree SQL错误处理 [英] fatfree SQL error handling
问题描述
如果由于任何原因,使用映射器创建条目时出错,我会收到错误。
我想做一个自定义通知并且如此优雅地失败了...
try {
$ request-> save();
} catch(异常$ e){
$ this-> utils-> errorNotify($ f3,'无法创建请求条目',http_build_query($ _ POST));
返回null;
}
这可能与F3?
\DB\SQL是PDO的一个子类,所以它可以抛出可捕获的PDO异常。由于默认情况下禁用它们,因此您需要先启用它们。这可以通过两种不同的方式完成:
-
在实例化时间内,对于所有交易:
$ db = new \DB\SQL($ dsn,$ user,$ pwd,array(\PDO :: ATTR_ERRMODE => \PDO :: ERRMODE_EXCEPTION ));
-
稍后在代码中,以每个交易为基础:
$ db-> setAttribute(\PDO :: ATTR_ERRMODE,\PDO :: ERRMODE_EXCEPTION);
一旦启用了PDO异常,只需捕获它们作为其他异常:
code> try {
$ db-> exec('INSERT INTO mytable(id)VALUES(?)','duplicate_id');
} catch(\PDOException $ e){
$ err = $ e-> errorInfo;
// $ err [0]包含错误代码(23000)
// $ err [2]包含驱动程序特定的错误消息(PRIMARY KEY必须是唯一的)
}
这也适用于DB映射器,因为它们依赖于相同的DB \SQL类:
$ ($ dsn,$ user,$ pwd,array(\PDO :: ATTR_ERRMODE => \PDO :: ERRMODE_EXCEPTION));$ mytable = new \DB\SQL\Mapper($ db,'mytable');
try {
$ mytable-> id ='duplicate_id';
$ mytable-> save(); //这将抛出一个异常
} catch(\PDOException $ e){
$ err = $ e-> errorInfo;
echo $ err [2]; // PRIMARY KEY必须是唯一的
}
If, for whatever reason, there is an error in creation of an entry using the mapper I get an error.
I'd like to do a custom notification and fail gracefully like so...
try {
$request->save();
} catch (Exception $e) {
$this->utils->errorNotify($f3,'could not create a request entry',http_build_query($_POST));
return null;
}
is this possible with F3?
\DB\SQL is a subclass of PDO so it can throw catchable PDO exceptions. Since these are disabled by default, you need to enable them first. This can be done in 2 different ways:
at instantiation time, for all transactions:
$db = new \DB\SQL($dsn, $user, $pwd, array( \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ));
later on in the code, on a per-transaction basis:
$db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
Once PDO exceptions are enabled, just catch them as other exceptions:
try {
$db->exec('INSERT INTO mytable(id) VALUES(?)','duplicate_id');
} catch(\PDOException $e) {
$err=$e->errorInfo;
//$err[0] contains the error code (23000)
//$err[2] contains the driver specific error message (PRIMARY KEY must be unique)
}
This also works with DB mappers, since they rely on the same DB\SQL class:
$db=new \DB\SQL($dsn,$user,$pwd,array(\PDO::ATTR_ERRMODE=>\PDO::ERRMODE_EXCEPTION));
$mytable=new \DB\SQL\Mapper($db,'mytable');
try {
$mytable->id='duplicate_id';
$mytable->save();//this will throw an exception
} catch(\PDOException $e) {
$err=$e->errorInfo;
echo $err[2];//PRIMARY KEY must be unique
}
这篇关于fatfree SQL错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!