How to Create Your Own Exception Classes in PHP

exceptions to create your own exception handler that will do your bidding when errors occur in third-party libraries:
class CustomException extends Exception
{
public function __construct($message, $code = 0)
{

parent::__construct($message, $code);

$msg .= __CLASS__ . “: [{$this->code}]: {$this->message}\n”;
$msg .= $this->getTraceAsString() . “\n”;
error_log($msg);
}

// overload the __toString() method to suppress any “normal” output
public function __toString() {
return $this->printMessage();
}

// map error codes to output messages or templates
public function printMessage() {

$usermsg = ”;
$code = $this->getCode();

switch ($code) {
case SOME_DEFINED_ERROR_CODE:
$usermsg = ‘Ooops! Sorry about that.’;
break;
case OTHER_DEFINED_ERROR_CODE:
$usermsg = “Drat!”;
break;
default:
$usermsg = file_get_contents(’/templates/general_error.html’);
break;
}
return $usermsg;
}

public static function exception_handler($exception) {
throw new CustomException($exception);
}

}

set_exception_handler(’CustomException’, ‘exception_handler’);

try {
$obj = new CoolThirdPartyPackage();
} catch (CustomException $e) {
echo $e;
}

Posted by Mahesh ( Tryangled )

Leave a Reply

You must be logged in to post a comment.