I am trying to catch when an email fails so that I can save the required data in my database and I can attempt to send at a later date.
I thought the following should work as it does when using save()
if ( $email->send() ) {
//..success - works..
} else {
//..fail - never gets here, stack trace
}
obviously you are not in debug mode there.
if you were, you would see that this actually throws an exception.
and you are catching sth there, just not the exception thrown :)
try this:
try {
$success = $email->send();
...
} catch (SocketException $e) { // Exception would be too generic, so use SocketException here
$errorMessage = $e->getMessage();
...
}
this way you can catch the exception and do sth here.
Related
I have a problem where I want to catch all exception except descendants of my custom exception.
Maybe bad design, but here it is (Simplified and names changed, but the code is quite accurate):
function doStuff()
{
try {
// code
if (something) {
// manually throw an exception
throw StuffError("Something is bad.");
}
// a third-party code, can throw exceptions
LibraryClass::arcaneMagic();
} catch (Exception $e) {
throw new StuffError("Error occured while doing stuff: "
. $e->getMessage());
}
}
/** My custom exception */
class StuffError extends Exception
{
function __construct($msg) {
parent::__construct('StuffError: ' . $msg);
}
}
However, the issue here is that I don't want the try-catch to intercept the manually throws StuffError. Or, seamlessly rethrow it or something.
As it is now, I'd get:
StuffError: Error occured while doing stuff: StuffError: Something is bad.
I want just:
StuffError: Something is bad.
How would I do it?
You can have multiple catch clauses, and the first one that matches will be the one that runs. So you could have something like this:
try {
do_some_stuff();
}
catch (StuffError $e) {
throw $e;
}
catch (Exception $e) {
throw new StuffError(Error occurred while doing stuff: " . $e->getMessage());
}
But you might want to rethink wrapping stuff like this. It obscures the real cause of the error. For one thing, you lose the stack trace. But it also complicates error handling, since now someone can't differentiate exception types the way you're trying to do, short of trying to parse the exception message (which is rather an anti-pattern in itself).
I might be misinterpreting you, but I think this is what you're looking for:
...
} catch (Exception $e) {
if (get_class($e) == 'StuffError' || is_subclass_of($e, 'StuffError')) {
throw $e;
} else {
throw new StuffError("Error occured while doing stuff: "
. $e->getMessage());
}
}
...
Replace your catch statement with the code above. It checks to see if the exception is a StuffError or a child class of StuffError. I'm still very confused at why you would need to throw a StuffError exception after you catch, but maybe that's just some weirdness coming from translating/cleaning your code.
This question is about the best way to execute code outside of try block only if no exception is thrown.
try {
//experiment
//can't put code after experiment because I don't want a possible exception from this code to be caught by the following catch. It needs to bubble.
} catch(Exception $explosion) {
//contain the blast
} finally {
//cleanup
//this is not the answer since it executes even if an exception occured
//finally will be available in php 5.5
} else {
//code to be executed only if no exception was thrown
//but no try ... else block exists in php
}
This is method suggested by #webbiedave in response to the question php try .. else. I find it unsatisfactory because of the use of the extra $caught variable.
$caught = false;
try {
// something
} catch (Exception $e) {
$caught = true;
}
if (!$caught) {
}
So what is a better (or the best) way to accomplish this without the need for an extra variable?
One possibility is to put the try block in a method, and return false if an exception is cought.
function myFunction() {
try {
// Code that throws an exception
} catch(Exception $e) {
return false;
}
return true;
}
Have your catch block exit the function or (re)throw/throw an exception. You can filter your exceptions as well. So if your other code also throws an exception you can catch that and (re)throw it. Remember that:
Execution continues if no exception is caught.
If an exception happens and is caught and not (re)throw or a new one throw.
You don't exit your function from the catch block.
It's always a good idea to (re)throw any exception that you don't handle.
We should always be explicit in our exception handling. Meaning if you catch exceptions check the error that we can handle anything else should be (re)throw(n)
The way I would handle your situation would be to (re)throw the exception from the second statement.
try {
$this->throwExceptionA();
$this->throwExceptionB();
} catch (Exception $e) {
if($e->getMessage() == "ExceptionA Message") {
//Do handle code
} elseif($e->getMessage() == "ExceptionB Message") {
//Do other clean-up
throw $e;
} else {
//We should always do this or we will create bugs that elude us because
//we are catching exception that we are not handling
throw $e;
}
}
When I execute my script something went wrong and an exception is thrown, but instead of stop the all script. How can I tell to zend to continue ?
This error appear when I fetch a mail I have a try catch block but it doesn't catch.
Fatal error: Uncaught exception 'Zend\Mail\Exception\RuntimeException' with message 'Line "X-Assp-Message/IP-Score:
Thanks.
My code is a simple class to fetch mail :
$listm = new Zend\Mail\Storage\Pop3(array('host' => $this->mServer,'user' => $this->mMail, 'password' => $this->mPassword));
foreach ($listm as $msgp3)
{
try
{
e($msgp3->from);
e($msgp3->to);
e($msgp3->subject);
e($msgp3->date);
e(strtotime($msgp3->date));
e($msgp3->messageid);
} catch (Exception $e) {
e($e->getMessage());
}
}
And my code stop at the 10em mail, so how make to tell to Zend to doesn't stop ?
The point of an Exception is to tell you that something bad has happened, and you need to build code to handle that properly. Without seeing your code, it's kinda hard to debug though.
If you want not to stop a process when a exception has been pointed. You can use a try and catch method. Like this:
try {
DoSomethingReallyBad()
}
catch(RuntimeException $e) {
// do nothing
}
// go further
I must say when a exception is called. The process of your last task is quitted.
Note: I didn't test this!
How are you catching the exception? Can you supply the try/catch code in your question please?
In Zend you need to use the full zend exception class that is being thrown. In this case it is Zend\Mail\Exception\RuntimeException, which becomes Zend_Mail_Exception_RuntimeException.
try
{
// ...
}
catch (Zend_Mail_Exception_RuntimeException $e)
{
// ...
}
I finally found where was my problem :
The error is return when i fetch the message here so in the for instruction :
foreach ($listm **as $msgp3**)
To catch any error when the message is fetch i have to fetch this way :
$maxMessage = count($messageList);
for($i = 0; $i < $maxMessage; $i++)
{
try{
$msgp3 = $messageList->getMessage($i);
//--- WORK ON msgp3
}catch(Exception $e) {
echo 'E2->'.$e->getMessage();
}
}
And now my script continue...
I'm trying to query a marketplace for an account that matches an e-mail address, and when it can't find a result, it's raising an uncaught exception despite my try/catch block.
try {
$vendor = $this->marketplace ->accounts ->query()
->filter(Balanced\Account::$f->email_address->eq($this->vendor['email']))
->one();
$this->balanced_vendor = $vendor;
return true;
} catch (Balanced\Exceptions\HTTPError $e) {
$this->notify('no-vendor', $e);
}
What might i be doing wrong ?
Thanks !
Looks like the Balanced\Core\Query class throws both Balanced\Exceptions\MultipleResultsFound and Balanced\Exceptions\NoResultFound from its one() method, not Balanced\Exceptions\HTTPError.
To fix your immediate problem, you should change your catch directive to:
} catch (Balanced\Exceptions\MultipleResultsFound $e) {
// handle multiple results..
} catch (Balanced\Exceptions\NoResultsFound $e) {
$this->notify('no-vendor', $e);
}
From the looks of it though, you attempted to use the Balanced\Exceptions\HTTPError as a catch all, which can be considered a lacking feature of the client. What I've done, is I've filed a Github issue for you that suggest all exceptions inherit from a base Balanced exception.
I hope this helps.
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 using 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 an Exception
But an Exception is not a PDOException.
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 PDOExceptions, 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.