fatfree SQL error handling

2019-02-15 06:03发布

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?

1条回答
在下西门庆
2楼-- · 2019-02-15 06:20

\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
}
查看更多
登录 后发表回答