i'm sending emails via phpmailer and i want to override the exceptions as when you send an email and that fail you can have the error message via :
echo json_encode"{$mail->ErrorInfo}";
but when the error is
"Empty body"
i would like to display something else.
Any solution ? Thanks
$new_msg = json_encode"{$mail->ErrorInfo}";
if ($new_msg == 'Empty body') {
throw new CustomException("You custom message ");
}
Wherever you are calling this function, catch the expectation there and show it to the user.
try {
if ($new_msg == 'Empty body') {
throw new CustomException("You custom message ");
}
} catch (CustomException $ex) {
//This is where you can have your own handling, exceptions that you want to handle separately
} catch (Exception $ex) {
// this part will handle general exceptions
// and show user some general error message
}
You can put your echo in a variable and then do an if check to display something else.
$new_msg = json_encode"{$mail->ErrorInfo}";
if ($new_msg == 'Empty body') {
echo 'You put here whatever you want';
} else {
echo json_encode"{$mail->ErrorInfo}";
}
Just catch the Exception and do something completely different!
try {
$something->thatWillThrowAnException();
} catch (Exception $e) {
// Do anything you want here!
}
Related
try {
if ($user_session_object['device_type'] == '1') {
$this->sendNotificationAndroidOne($notificationData);
}
throw new Exception("newInner");
//throw new Exception("newInner");
if ($user_session_object['device_type'] == '2') {
$this->sendNotificationIphone($notificationData);
}
}catch(Exception $ex){
echo 'Exception occur while send push notification';
exit;
}
Getting error: Exception' not found in file. Thanks in advance
This is likely a namespace issue (nothing to do with Zend Framework), so you want throw new \Exception("newInner"); and catch(\Exception $ex).
Otherwise, please add the full error message to your question.
As per your code "throw new Exception("newInner")" it have not makes any sence inside try{} block, because whenever an exception will be found catch(){} block will be called.
You should use try---catch like below.
try{
if ($user_session_object['device_type'] == '1') {
$this->sendNotificationAndroidOne($notificationData);
}
if ($user_session_object['device_type'] == '2') {
$this->sendNotificationIphone($notificationData);
}
}catch (\Exception $e) {
var_dump($e->getMessage());
var_dump($e->getCode());
exit;
}
I using standard PHP function:
try
{
}
catch (Exception $exc)
{
echo $exc->getMessage();
}
...
throw new Exception('Error Message');
to validate data and return various messages to the user. And it works perfectly. But with with this method everything will stops if new Exception been trowed (which is right). But I would like to use soft validation (when error appears but user can process forward). Does PHP have something like that?
I think this will help you to understand how the try...catch works and how to get the exception messages. Read more about exception here http://php.net/manual/en/language.exceptions.php
Demo code:
$exception = [];
try {
function1();
function2();
}
catch(Exception $e){
$exception['msg'] = $e->getMessage();
$exception['code'] = $e->getCode();
}
function3();
print '<pre>';
print_r($exception);
print '</pre>';
Here, the function3() will always be executed. But if the function1() throws an exception, function2() will not executed further.But If exception occurs you can receive the $exception data.
Try to gather the error messages to an array, and return that.
if(strlen($username) < 3) $errors[] = "Username is too short";
if(strlen($password) < 3) $errors[] = "Password is too short";
return $errors;
I'm trying to customize error messages.
For handling errors i used "try/catch" block according to this Recurly documentation, like this for example:
try {
$account = Recurly_Account::get('my_account_id');
$subscription = new Recurly_Subscription();
$subscription->account = $account;
$subscription->plan_code = 'my_plan_code';
$subscription->coupon_code = 'my_coupon_code';
/* .. etc .. */
$subscription->create();
}
catch (Exception $e) {
$errorMsg = $e->getMessage();
print $errorMsg;
}
I wanted use code in catch block like this:
catch (Exception $e) {
$errorCode = $e->getCode();
print $myErrorMsg[$errorCode]; // array of my custom messages.
}
But getCode() method always returns zero for all possible errors.
My question for Recurly Team (or who there in this theme):
How i get error code for errors? Or please explain me how i can resolve this topic. Thanks!
If you look at the PHP Client on Github and you search for "throw new" which is what is done when an exception is thrown you'll see that they don't set the exception error code the second parameter of the exception constructor method.
Recurly PHP Client on Github: https://github.com/recurly/recurly-client-php/search?utf8=%E2%9C%93&q=throw+new
PHP Exception documentation: http://php.net/manual/en/language.exceptions.extending.php
Therefore, you'll either need to catch more exceptions based on their name
i.e.
catch (Recurly_NotFoundError $e) {
print 'Record could not be found';
}
OR
look at the exception message and compare it
catch (Exception $e) {
$errorMessage = $e->getMessage();
if($errorMessage=='Coupon is not redeemable.')
{
$myerrorCode=1;
}
//Add more else if, or case switch statement to handle the various errors you want to handle
print $myErrorMsg[$myerrorCode]; // array of my custom messages.
}
Suppose to have a PHP code inside a try...catch block. Suppose that inside catch you would like to do something (i.e. sending email) that could potentially fail and throw a new exception.
try {
// something bad happens
throw new Exception('Exception 1');
}
catch(Exception $e) {
// something bad happens also here
throw new Exception('Exception 2');
}
What is the correct (best) way to handle exceptions inside catch block?
Based on this answer, it seems to be perfectly valid to nest try/catch blocks, like this:
try {
// Dangerous operation
} catch (Exception $e) {
try {
// Send notification email of failure
} catch (Exception $e) {
// Ouch, email failed too
}
}
You should not throw anything in catch. If you do so, than you can omit this inner layer of try-catch and catch exception in outer layer of try-catch and process that exception there.
for example:
try {
function(){
try {
function(){
try {
function (){}
} catch {
throw new Exception("newInner");
}
}
} catch {
throw new Exception("new");
}
}
} catch (Exception $e) {
echo $e;
}
can be replaced to
try {
function(){
function(){
function (){
throw new Exception("newInner");
}
}
}
} catch (Exception $e) {
echo $e;
}
You have 2 possible ways:
You exit the program (if it is severe) and you write it to a log file and inform the user.
If the error is specifically from your current class/function,
you throw another error, inside the catch block.
You can use finally. Code in this branch will be executed even if exception is thrown within catch branch
Is it possible to display all catches instead of only one? In the example below, what if both the username and email are wrong, can I output both instead of just one.
try {
// Code here
}
catch(WrongUsername $e) {
echo 'Your username is wrong.'
}
catch(WrongEmail $e) {
echo 'Your email is wrong too.'
}
You can probably loop thru all the validation rules and cathc all errors.
$errors = [];
foreach($rules as $rule){
try{
validate($input, $rule);
}catch(Exception $e){
$errors[] = $e->getMessage();
}
}
But then I don't see any reason to use try-catch at all.
This doesn't really make a lot of sense within PHP - it's dynamically, not fixed typed, and does not support overloading. In your example is 'WrongEmail' the class of the exception or the exception message? Is there a benefit to sub-classing exceptions?
If it's the message property of the exception, then change it to use something more informative...
try {
...
if (!preg_match($pattern, $username))
throw new Exception('Your username is wrong.');
...
} catch ($e) {
echo $e->message;
}
If you have a good reason for sub-classing your exceptions...
try {
...
} catch ($e) {
switch (get_class($e)) {
case 'WrongUsername':
echo 'Your username is wrong.';
break;
case 'WrongEmail':
echo 'Your email is wrong.'
break;
...
}
}
But exceptions are part of a flow control structure - when you throw an exception you change the flow of execution. A try{} block will never raise more than one exception. In terms of programming style it's debatable whether you should actually use exceptions at all for this kind of operation.
If you want to check a set of pre-conditions and deal with each failed requirement then don't use this construct.