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;
Related
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!
}
I wonder if it's posible to get all the exceptions throwed.
public function test()
{
$arrayExceptions = array();
try {
throw new Exception('Division by zero.');
throw new Exception('This will never get throwed');
}
catch (Exception $e)
{
$arrayExceptions[] = $e;
}
}
I have a huge try catch block but i want to know all the errors, not only the first throwed. Is this possible with maybe more than one try or something like that or i am doing it wrong?
Thank you
You wrote it yourself: "This will never get throwed" [sic].
Because the exception will never get thrown, you cannot catch it. There only is one exception because after one exception is thrown, the whole block is abandoned and no further code in it is executed. Hence no second exception.
Maybe this was what the OP was actually asking for. If the function is not atomic and allows for some level of fault tolerance, then you can know all the errors that occurred afterwards instead of die()ing if you do something like this:
public function test()
{
$arrayExceptions = array();
try {
//action 1 throws an exception, as simulated below
throw new Exception('Division by zero.');
}
catch (Exception $e)
{
//handle action 1 's error using a default or fallback value
$arrayExceptions[] = $e;
}
try {
//action 2 throws another exception, as simulated below
throw new Exception('Value is not 42!');
}
catch (Exception $e)
{
//handle action 2 's error using a default or fallback value
$arrayExceptions[] = $e;
}
echo 'Task ended. Errors: '; // all the occurred exceptions are in the array
(count($arrayExceptions)!=0) ? print_r($arrayExceptions) : echo 'no error.';
}
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.
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;
}
}
I'd like to use an exception for error handling in a part of my code but if the code should fail, I would like the script to continue. I want to log the error though. Can someone please help me figure this out?
try{
if($id == 4)
{
echo'test';
}
}
catch(Exception $e){
echo $e->getMessage();
}
echo'Hello, you should see me...'; <------ I never see this.. No errors, just a trace.
You have to catch the exception :
// some code
try {
// some code, that might throw an exception
// Note that, when the exception is thrown, the code that's after what
// threw it, until the end of this "try" block, will not be executed
} catch (Exception $e) {
// deal with the exception
// code that will be executed only when an exception is thrown
echo $e->getMessage(); // for instance
}
// some code, that will always be executed
And here are a couple of things you should read :
Exceptions in the PHP manual
Exceptional PHP: Introduction to Exceptions
In the code that is calling the code that may throw an Exception do
try {
// code that may break/throw an exception
echo 'Foo';
throw new Exception('Nothing in this try block beyond this line');
echo 'I am never executed';
throw new CustomException('Neither am I');
} catch(CustomException $e) {
// continue here when any CustomException in try block occurs
echo $e->getMessage();
} catch(Exception $e) {
// continue here when any other Exception in try block occurs
echo $e->getMessage();
}
// script continues here
echo 'done';
Output will be (adding line breaks for readability):
'Foo' // echoed in try block
'Nothing in this try block beyond this line' // echoed in Exception catch block
'done' // echoed after try/catch block
Try/Catch Blocks may also be nested. See Example 2 in the PHP Manual page linked above:
try{
try {
throw new Exception('Foo');
echo 'not getting here';
} catch (Exception $e) {
echo $e->getMessage();
}
echo 'bar';
} catch (Exception $e) {
echo $e->getMessage();
}
echo 'done';
'Foo' // echoed in inner catch block
'bar' // echoed after inner try/catch block
'done' // echoed after outer try/catch block
Further reading at DevZone:
http://devzone.zend.com/node/view/id/666
http://devzone.zend.com/article/679-Exceptional-Code---PART-2
http://devzone.zend.com/node/view/id/652
http://devzone.zend.com/article/653-PHP-101-PART-12-BUGGING-OUT---PART-2