problem using try, throw catch in PHP for error handling
for the first time i came across try, throw catch statement in PHP, and i felt this could be the better way for handling errors as i was quite messing my error handlers with lots of if else statements, however as i am performing CRUD operations on my script i wanted my error handlers to perform two task.
- display the user readable or custom error message back to the user.
- catch all the error in a file for me to read.
i am us开发者_Python百科ing the following code..
try
{
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if($cname == $name)
{
throw new Exception('Sorry, Please Change the value to update ');
}
$sth = $dbh->prepare("UPDATE countries SET name = :name WHERE id = :cid");
$sth->bindParam(':name', $name);
$sth->bindParam(':cid', $cid);
$sth->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
file_put_contents("resources/logs/Connection-log.txt", DATE.PHP_EOL.$e->getMessage().PHP_EOL.PHP_EOL, FILE_APPEND);
}
if the condition $cname == $name is true i just want to display the error 'Sorry, Please Change the value to update, however this is not happening here, instead it throws the Fatal Error with this message.
Fatal error: Uncaught exception 'Exception' with message 'Sorry, Please Change the value to update ' in /Applications/MAMP/htdocs/kokaris/administrator/resources/library/models/countries.php:24 Stack trace: #0 /Applications/MAMP/htdocs/kokaris/administrator/location-manager.php(43): include() #1 {main} thrown in /Applications/MAMP/htdocs/kokaris/administrator/resources/library/models/countries.php on line 24
how do i achieve this?
thank you..
Your catch is catching a PDOException
:
catch(PDOException $e)
While you are throwing a Exception
:
throw new Exception('Sorry, P...
PDOException
is a sub-class of Exception
, which means that :
- A
PDOException
is anException
- But an
Exception
is not aPDOException
.
So, when you are trying to catch a PDOException
, your catch
will not also catch Exception
.
If you want your Exception
to be catched, you must use something like this :
try {
}
catch (PDOException $e) {
// deal with PDOException
}
catch (Exception $e) {
// deal with all other kinds of exceptions
}
In this case, the catch
PDOException
can be avoided, if you do not want to do some special treatment for PDOException
s, and just want all exceptions to be dealt with the same way :
try {
}
catch (Exception $e) {
// deal with all kinds of exceptions
}
You are throwing an Exception
but catching a PDOException
.
You should catch the same as you throw, so you might want to change your catch to:
catch(Exception $e)
Or if you also want to catch that PDOException
and not do the file_put_contents
for your own excpetion, add a catch
for your specific Exception
.
YOu could ofcourse also change your throw to PDOException
, same thing basically.
精彩评论