Domanda

I am developing an in-house website that computes certain values. I need to show the users the errors gone from the computation with simple message rather than the PHP error. I am also studying throwing exception in PHP Is this a good way to re-throw an exception in this case?

È stato utile?

Soluzione

Yes it is possible and it is a good way.

<?php
 class customException extends Exception
  {
  public function errorMessage()
    {
    //error message
    $errorMsg = $this->getMessage().' is not a valid E-Mail address.';
    return $errorMsg;
    }
  }

$email = "someone@example.com";

try
  {
  try
    {
    //check for "example" in mail address
    if(strpos($email, "example") !== FALSE)
      {
      //throw exception if email is not valid
      throw new Exception($email);
      }
    }
  catch(Exception $e)
    {
    //re-throw exception
    throw new customException($email);
    }
  }

catch (customException $e)
  {
  //display custom message
  echo $e->errorMessage();
  }
     ?>

Example explained: The code above tests if the email-address contains the string "example" in it, if it does, the exception is re-thrown:

  1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class
  2. The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
  3. The $email variable is set to a string that is a valid e-mail address, but contains the string "example"
  4. The "try" block contains another "try" block to make it possible to re-throw the exception
  5. The exception is triggered since the e-mail contains the string "example"
  6. The "catch" block catches the exception and re-throws a "customException"
  7. The "customException" is caught and displays an error message

If the exception is not caught in its current "try" block, it will search for a catch block on "higher levels".

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top