Forum Moderators: coopster
I have been told not to use try and catch in the conection as this is not safe or good, ...
...and php should handle the errors.
posts: 2824
msg:4640851new post indicator10:52 pm on Jan 28, 2014 (utc +1)
I have been told not to use try and catch in the conection as this is not safe or good, ...
Hhhmm, I thought this was the good thing with PDO; the exception handling? What else do they propose to do?
As the manual says:
"PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails."
If you don't use a try...catch block then your "page just stops to load" if there is a connection error - oh wait, hang on! ;)
...and php should handle the errors.
? In what way should it "handle the errors"?
If your application does not catch the exception thrown...
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
} "// DO NOT USE THIS! It's is a negative example
try {
$database->do_something();
} catch (PDOException $error) {
die('Dear users of the Internet, this database error just happened on my server: ' . $error->getMessage());
} "
try - catch should be used, just don't print the getMessage().
try {
$database->conecxion here;
} catch (PDOException $error) {
die('My message here: ' . $errorlog->Output("conexion/error/".$error.".log");
} You create your own/custom error handler using the set_error_handler() [php.net] function and likewise to create your own exception handler you use set_exception_handler() [php.net]. You can pass a callback to these functions that handle everything, write errors to a log file, send emails, etc. You set this up once at the very start of your application. You don't need to touch php.ini
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: ";
die();
try {
$database->conecxion here;
} catch (PDOException $error) {
die('My message here: ' . $errorlog->Output("conexion/error/".$error.".log");
}
Suppose not to display the internal message, only my customized I could do:
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: ";
die();
The issue the author of
// DO NOT USE THIS! It's is a negative example
try {
$database->do_something();
} catch (PDOException $error) {
die('Dear users of the Internet, this database error just happened on my server: ' . $error->getMessage());
}
raises is that one should NOT print full error messages to users.