Is there a way to setup a Pdo object to throw a custom exception instead of the default PDOException?
For example:
class MyCustomDbException extends PDOException{}
$pdo = new Pdo("mysql:host=localhost;dbname=myapp", "user_name", "secret_password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EXCEPTION_CLASS, "MyCustomDbException");
try {
// Code is here
} catch (PDOException $e) {
// See exception manual if you want to path through message or anything else from pdo exception.
throw new YourException('PDO exception was thrown');
}
http://php.net/manual/en/language.exceptions.extending.php
to see how you can path through parameters.
Related
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
}
I can enable PDO to throw error as exceptions to PDOException class.
Can I make it to throw it to my exception class?
Right now I have to code like this:
try {
$sql = "query";
$zap = $pdo->query($sql);
$sql_d=array();
if ($zap->execute($sql_d)) {
}
} catch (\PDOException $e) {
throw new dbException($zap->errorInfo(), $sql);
}
I want to PDO throw error to dbException class - not PDOException.
I have a database class dbconnect.php, and processform.php. Inside dbconnect.php there is a method for connecting to the database.
If there's an error, how do I throw an exception? Where do I put the try catch block, in the processform.php? People say I shouldn't echo an error directly from inside the class. Here's an example:
<?php
// dbconnect.php
class DbConnect
{
public function open_connection()
{
/* Should I do it like this? */
$this->conn = PDO($dsn, $this->username, $this->password);
if (!$this->conn) {
throw new Exception('Error connecting to the database.');
}
/* Or like this */
try {
$this->conn = PDO($dsn, $this->username, $this->password);
} catch (PDOException $e) {
echo 'Error: ', $e->getMessage(), '<br>';
}
}
?>
// processform.php
<?php
require_once 'dbconnect.php';
$pdo = new DbConnect($host, $username, $password);
try {
$pdo->open_connection();
} catch (PDOException $e) {
echo 'Error connecting to the database.');
}
?>
I really want to learn the correct way of implementing the try catch in my code.
You don't have to throw an exception manually, especially on a successful connect :-)
Instead you need to tell PDO that it needs to throw exceptions when something goes wrong and you can do that when you open your database connection:
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->conn = new PDO($dsn, $this->username, $this->password, $options);
Now you can put everything in try / catch blocks but that is not even necessary; if you don't do that, php will show you unhandled exceptions complete with a stack trace when you don't catch them manually.
And when you decide you want to fine-tune your error handling for your visitors, you can set your own exception handler using set_exception_handler(). That way you can handle everything at one place instead of wrapping different sections in try / catch blocks. Should you prefer that of course.
In my practice, I prefer to catch exception in bottom. I mean, second way in your DbConnect.
You can output error message to error log. And return an error code to front-end. So the front-end knows how to tell users an error occours in a friendly way.
What's more, you can use global error handler such as set_error_handler/set_exception_handler to do this. Redirect to an error page when error occours.
What im trying to achieve here , is when the pdo connection throws an exception , my custom exception handler takes the message and passes it on so i can catch it with my custom exception handler.
try {
$mysqli = new PDO('mysql:host='.THOST.';dbname='.TDB.'', TUSER, TPASS);
}
catch (PDOException $e) {
$a = $e->getMessage();
throw new customException ( "Failed to connect to MySQL:". $a );
die();
}
catch (customException $e){
echo $e->errorMessage();
}
BUT it returns this error :
Fatal error: Uncaught exception 'customException' with message ......
Wrap it in another try-catch block.
try {
try {
$mysqli = new PDO('mysql:host='.THOST.';dbname='.TDB.'', TUSER, TPASS);
} catch(PDOException $e) {
$a = $e->getMessage();
throw new customException ( "Failed to connect to MySQL:". $a );
}
} catch(customException $e) {
echo $e->errorMessage();
// Do what you want
}
You are confusing custom exception handler with custom exception class. You need the former one and the other answer is wrong.
Explanation.
In your application code you have to writing one single line only:
$pdo = new PDO('mysql:host='.THOST.';dbname='.TDB.'', TUSER, TPASS);
without multiple tries and stuff. Just the code you need to run.
While all the handling logic goes into handler
I'm building a custom exception class to manage all exceptions:
class MyExceptions extends Exception
{
public function __construct($message = 'Unkown errror', $code = -1, Exception $previous = null) {
echo 'init!';
parent::__construct($message, $code, $previous);
}
}
Now, when a PDOException occurs, I want to re-throw it to MyExceptions:
class myDB
{
private $db;
public function dbConnect() {
try {
$this->db = new PDO('mysql:host=localhost;dbname=db;charset=utf8', 'user', 'pass');
}
catch (PDOException $e) {
throw new MyExceptions($e);
}
/* Updated */
catch (MyExceptions $e) {
echo 'caught!';
}
}
}
The problem is that when a db connection exception rises, I get the following fatal error on screen:
init!
Fatal error: Uncaught exception 'MyExceptions' with message...
So, the exception is not caught, although the MyExceptions __construct() is called (see the 'init!' displayed).
Every bit of resource I read points to the exact implementation as mine, I have no idea what I'm doing wrong.
You need
try {
try {
$this->db = new PDO('mysql:host=localhost;dbname=db;charset=utf8', 'user', 'pass');
} catch (PDOException $e) {
throw new MyExceptions($e);
}
} catch (MyExceptions $f) {
echo 'caught!';
}
Sequential catch blocks are for different types of exceptions thrown within the try.
You are throwing it:
throw new MyExceptions($e);
^^^^^
And then you don't catch it. So what do you wonder about?
Also you should add the previous exception at third position (for previous) instead of the first position (for message).
It doesn't go through all the catch blocks. Only the first one that matches. If you then throw another exception inside a catch block, you'd have to catch it in another try block around the first one.