Complete SQL error handling

If, for any reason, an error occurs while creating a record using the cartographer, I get an error.

I would like to make a custom notification and fail gracefully ...

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?

+3


source to share


1 answer


\ DB \ SQL is a PDO subclass, so it can throw catching PDO exceptions. Since they are disabled by default, you need to enable them first. This can be done in two different ways:

  • during instantiation for all transactions:

    $db = new \DB\SQL($dsn, $user, $pwd, array( \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ));

  • further in the code, for each transaction:

    $db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

Once PDO exceptions are enabled, simply catch them like 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 sample DBs as 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
}

      

+7


source







All Articles