note 110134 deleted from class.errorexception by aharvey

From: Date: Mon, 24 Sep 2012 01:22:23 +0000
Subject: note 110134 deleted from class.errorexception by aharvey
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-190978@lists.php.net to get a copy of this message
Note Submitter: xianrenb at gmail dot com ---- Example of using both $code and $severity: <?php define('CODE_AMOUNT_TOO_SMALL', 1000); define('CODE_NOT_ENOUGH_BALANCE', 2000); set_error_handler(function ($errno, $errstr, $errfile, $errline) { throw new ErrorException($errstr, 0, $errno, $errfile, $errline); }); class MyClass { private $balance; public function __construct($initBalance) { $this->balance = $initBalance; } public function getBalance() { echo("getBalance:\n"); echo('*balance: ' . $this->balance . "\n"); } public function run($i) { if ($i === 0) { $this->throwError(); } else if ($i === 1) { $this->withdraw(0.01); $this->getBalance(); } else if ($i === 2) { $this->withdraw(100); $this->getBalance(); } else if ($i === 3) { $this->withdraw(10); $this->getBalance(); } else { $this->wrongCoding(); } } public function test() { $this->getBalance(); for ($i = 0; $i < 5; ++$i) { try { $this->run($i); } catch (ErrorException $e) { if ($e->getSeverity() === E_ERROR) { echo("E_ERROR triggered.\n"); } else if ($e->getSeverity() === E_WARNING) { echo("E_WARNING triggered.\n"); } else if ($e->getSeverity() === E_USER_NOTICE) { if ($e->getCode() === CODE_AMOUNT_TOO_SMALL) { echo("Handling user error: amount too small.\n"); } else if ($e->getCode() === CODE_NOT_ENOUGH_BALANCE) { echo("Handling user error: not enough balance.\n"); } } } } } public function throwError() { echo("throwError:\n"); throw new ErrorException(); } public function withdraw($amount) { echo("withdraw:\n"); echo('*amount: ' . $amount . "\n"); if ($this->balance < $amount) { throw new ErrorException('Not enough balance', CODE_NOT_ENOUGH_BALANCE, E_USER_NOTICE); } else if ($amount < 1) { throw new ErrorException('Amount too small', CODE_AMOUNT_TOO_SMALL, E_USER_NOTICE); } else { $this->balance -= $amount; } } public function wrongCoding() { echo("wrongCoding:\n"); strpos(); } } $myClass = new MyClass(99); $myClass->test(); ?> Running results: getBalance: *balance: 99 throwError: E_ERROR triggered. withdraw: *amount: 0.01 Handling user error: amount too small. withdraw: *amount: 100 Handling user error: not enough balance. withdraw: *amount: 10 getBalance: *balance: 89 wrongCoding: E_WARNING triggered.

« previous php.notes (#190978) next »