Page 1 of 1

Exception Handleing, Multiple Errors

Posted: Sat Jan 09, 2010 6:47 pm
by synical21
I been reading about exception handleing to add to my web application, I can make one exception easily but when i try to create multiple conditions with unique error messages per condition i fail, the result i get is no matter what exception is triggered only the last catch block/error message is displayed. Here is the code..

Code: Select all

 
  <?php
  
  // Get and strip values  from form 
$title= $data['title'];
$descript= $data['descript'];
$proof= $data['proof'];
$min= $data['min'];
$amountworkers= $data['amountworkers'];
$perperson= $data['perperson'];
$createuser_id= $data['createuser_id'];
$user_name= $data['user_name'];
$ujob_id= $data['id'];
$feature= $data['feature'];
$tbl_name = "fulldata";
 
// Check the form token
if(isset($data['proof']) && isset($data['title']) && isset($data['descript']) && isset($data['title']) && isset($data['min']) && isset($data['amountworkers']) && isset($data['perperson']) && isset($data['createuser_id']) && isset($data['user_name']) && isset($data['id']))
{
    if($data['token'] != $_SESSION['token'])
    {
        die('Invalid Token');
    }
    
    // token is now valid, process rest of form
    
    if (isset($data['submit'])){
 
        if ($data['done']){
            echo "The form has already been processed";}
 
        else { 
 
 
 
 
// calculate the cost of the job
$total_cost = round(($data['amountworkers'] * $data['perperson'] + $data['feature']) * 1.05, 2);
$user_cost = $_SESSION['user_money'];
 
try {
        if ($perperson < 0.10) {
         throw new Exception("perperson is to small"); // more than 0.10 per person?
       }
 
 
        if ($total_cost > $user_cost) {
         throw new Exception("incorrect funds"); // does the user have the correct amount of money?
       }
 
// if the user does have enough money process the update in DB 
else{
    
    session_start();
    $_SESSION['user_money'] = round($user_cost - $total_cost, 2);
 
     
      $sql = "UPDATE `users`
    SET users.user_money = round($user_cost - $total_cost, 2)
  WHERE users.id = '$_SESSION[user_id]'";
 $result = mysql_query($sql)
     or die('Invalid query: ' . $sql . ' - Error is ' . mysql_error());
     
    
}
 
 
// Insert data into mysql 
$sql= mysql_query("INSERT INTO $tbl_name(job_id, title, descript, proof, min, amountworkers, perperson, createuser_id, user_name, date)VALUES('$ujob_id', '$title', '$descript', '$proof', '$min', '$amountworkers', '$perperson', '$createuser_id', '$user_name',now())") or die( mysql_error() );
 
 
// has the user paid for the service or isit free bouns job?
 if ($total_cost > 2.00)
     {
         $sql = "UPDATE `fulldata`
    SET fulldata.deposit = 1
  WHERE fulldata.job_id = '$ujob_id'";
 $result = mysql_query($sql)
     or die('Invalid query: ' . $sql . ' - Error is ' . mysql_error());
     }
     
      if ($feature > 0.10)
     {
         $sql = "UPDATE `fulldata`
    SET fulldata.feature = 1
  WHERE fulldata.job_id = '$ujob_id'";
 $result = mysql_query($sql)
     or die('Invalid query: ' . $sql . ' - Error is ' . mysql_error());
     }
     
 
// if successfully insert data into database, displays message "Successful". 
if($sql){
    
echo "Thank you for submiting your job, our team will now take a look and approve very soon ";
echo "<BR>";
echo "$feature";
echo "<a href='/jobs.php'>Click here to go back to Minute Workers</a>";
}
 
else {
echo "ERROR";
}
    
        } catch (Exception $e) {
     
    // There has been an error
    echo "Each person needs more than 0.10";
 
} catch (Exception $e) {
     
    // There has been an error
    echo "You have insufficient funds to create this job, please allow room for a 5% charge onto your job total cost.";
    echo "<BR>";
    echo "<BR>";
    echo "Your total cost is: <b>$$total_cost</b>";
    echo "<BR>";
    echo "Your current deposit amount is: <b>$$_SESSION[user_money]</b>";
    echo "<BR>";
    echo "<BR>";
    echo "Please click back and try again.";
    
 
    }
}
    }
}
 
line 41-49: I am trying to create the conditions
line 105-END: I am trying to catch the conditions

So the problem is if one of the exceptions is triggered it is always the secound catch blocks error messaged displayed. How can i have each condition with its own error message when triggered.

Re: Exception Handleing, Multiple Errors

Posted: Sat Jan 09, 2010 6:56 pm
by Darhazer
The catch is per try block or per Exception class. It make no sense to have multiple catch blocks for one try, if all exceptions are from the same class.

Re: Exception Handleing, Multiple Errors

Posted: Sat Jan 09, 2010 6:59 pm
by synical21
Hmm so i need to create a new exception class :s I hate classes I really need to learn object oriented programming.. Can i have some help creating a new class for each exception please

Re: Exception Handleing, Multiple Errors

Posted: Sat Jan 09, 2010 7:09 pm
by Darhazer
Actually you have to pay more attention about structuring and formatting code.
You can check all your variables with single isset() code -just pass them all, separated with comma:

Code: Select all

if(isset($data['proof'], $data['title'], $data['descript'], $data['title'], $data['min'], $data['amountworkers'], $data['perperson'], $data['createuser_id'], $data['user_name'], $data['id']))
 {
As for the exception, in your case I'd use the second exception parameter - the code, and in the catch block use switch on the code to load the correct error message:

Code: Select all

switch ($e->getCode()) {
...
}

Re: Exception Handleing, Multiple Errors

Posted: Sat Jan 09, 2010 7:22 pm
by synical21
Sorry I am failing to understand what you are saying (1am lol), so using the block of the secound exception i can use switch to generate the correct error message? I just dont know what you mean by using the secound exception parameter. :banghead:

Re: Exception Handleing, Multiple Errors

Posted: Sun Jan 10, 2010 11:29 am
by synical21
Bump, i still cant get this working :(

Re: Exception Handleing, Multiple Errors

Posted: Sun Jan 10, 2010 1:14 pm
by Darhazer
Please, read more about the exceptions ...
http://php.net/manual/en/language.exceptions.php

Each exception have a message and a code. Relying on string messages is not a good idea, it's better to rely on the code (since you can easily decide to change the message and to forgot to change it in the catch block)

You can also read about the switch statement
http://php.net/manual/en/control-structures.switch.php

Re: Exception Handleing, Multiple Errors

Posted: Sun Jan 10, 2010 1:44 pm
by VladSun
Darhazer wrote:The catch is per try block or per Exception class. It make no sense to have multiple catch blocks for one try, if all exceptions are from the same class.
Exactly!

@synical21 - take a look at this:

Code: Select all

class MyException1 extends Exception {};
class MyException2 extends Exception {};
 
class Myclass
{
 
/**
 *
 * @throws MyExecption1
 * @throws MyException2
 * @param int $a
 */
  function myMethod($a)
  {
    if (!is_numeric($a))
      throw new MyException1('MyException1 occured', 1001);
    if ($a === 0)
      throw new MyException2('MyException2 occured', 1002);
 
    // Do something with $a
  }
}
 
 
$class = new Myclass();
try
{
   $class->myMethod(0);
}
catch (MyException1 $e)
{
  var_dump($e);
  // Do something 1
}
catch (MyException2 $e)
{
  var_dump($e);
  // Do something 2
}
 
You can even override the Exception class methods in your custom exception classes.

Re: Exception Handleing, Multiple Errors

Posted: Sun Jan 10, 2010 3:02 pm
by synical21
Thanks i followed that kind of logic and created custom classes what were extended then added unique error message for each class (Dont know if thats how you wanted me to do it but it is working flawlessly now). Thank you for all the help you two :drunk: