Elegant Ways of Handling PHP Errors and Exceptions
Upcoming SlideShare
Loading in...5
×
 

Elegant Ways of Handling PHP Errors and Exceptions

on

  • 53,622 views

Murphy was right: things will go wrong in any given situation if you only give them a chance. Therefore this session will discuss ways of limiting the risk of things going wrong in your application.

Murphy was right: things will go wrong in any given situation if you only give them a chance. Therefore this session will discuss ways of limiting the risk of things going wrong in your application.

Statistics

Views

Total Views
53,622
Views on SlideShare
52,877
Embed Views
745

Actions

Likes
33
Downloads
619
Comments
2

22 Embeds 745

http://phpcollection.com 358
http://devhub-polycademy.pagodabox.com 111
http://www.scoop.it 71
http://thegeekhead.blogspot.com 45
http://www.phpcollection.com 45
http://www.slideshare.net 44
http://yogeshnayi7.wordpress.com 23
http://devhub-polycademy.gopagoda.com 18
http://www.prosoxi.com 5
https://blackboard.strayer.edu 4
http://thegeekhead.blogspot.in 4
http://www.e-presentations.us 3
http://static.slidesharecdn.com 2
https://twitter.com 2
http://www.thegeekhead.co.cc 2
http://thegeekhead.blogspot.com.au 2
http://thegeekhead.blogspot.it 1
http://thegeekhead.blogspot.com.es 1
http://thegeekhead.blogspot.com.br 1
http://thegeekhead.blogspot.de 1
http://thegeekhead.blogspot.fr 1
http://community.sitepoint.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Elegant Ways of Handling PHP Errors and Exceptions Elegant Ways of Handling PHP Errors and Exceptions Presentation Transcript

  • ELEGANT WAYS OF HANDLING PHP ERRORS AND EXCEPTIONS By Eddo Rotman   Copyright © 2008, Zend Technologies Inc.
  • Errors Basically errors can be of one of two types • External Errors • Logic Errors (a.k.a. Bugs) What about these error types? • External Errors will always occur at some point or another • External Errors which are not accounted for are Logic Errors • Logic Errors are harder to track down 2| Sep 17, 2008 |
  • PHP Errors Four levels of error severity to start with • Strict standard problems (E_STRICT) • Notices (E_NOTICE) • Warnings (E_WARNING) • Errors (E_ERROR) 3| Sep 17, 2008 |
  • PHP Errors (cont) // E_NOTICE $x = $y + 3; // E_WARNING $fh = fopen('thisisnotarealfile', 'r'); // E_ERROR nonExistingFunction(); Notice: Undefined variable: y in /home/eddo/workspaces/neon/ZendCon08­ ServerIndie/xxx.php on line 6 Warning: fopen(thisisnotarealfile) [function.fopen]: failed to open  stream: No such file or directory in  /home/eddo/workspaces/neon/ZendCon08­ServerIndie/xxx.php on line 8 Fatal error: Call to undefined function nonexistingfunction() in  /home/eddo/workspaces/neon/ZendCon08­ServerIndie/xxx.php on line 10 4| Sep 17, 2008 |
  • User Triggered Errors Almost the same as the ones in the previous slides • User triggered notice (E_USER_NOTICE) • User triggered warning (E_USER_WARNING) • User triggered error (E_USER_ERROR) Triggering them is done using trigger_error() For example: function getFooPlusOne($foo) { if (3 > $foo) { trigger_error('foo has to be greater than 3', E_USER_ERROR); } return ($foo + 1); } 5| Sep 17, 2008 |
  • Additional Error Types Catchable fatal error • E_RECOVERABLE_ERROR – a probably dangerous error occurred. If not handled by the user, the application will abort as if this was an E_ERROR Parsing errors • E_PARSE – there is a syntactic error found while parsing the script. This is a fatal error Compilation errors • E_COMPILE_ERROR – a fatal error occurred in the engine while compiling the script • E_COMPILE_WARNING - a nonfatal error occurred in the engine while compiling the script PHP core errors • E_CORE_ERROR – a fatal runtime error occurred in the engine • E_CORE_WARNING – a nonfatal runtime error occurred in the engine 6| Sep 17, 2008 |
  • Error Reporting Settings Setting which errors PHP will report is done through the error_reporting directive • in php.ini file error_reporting = E_ALL & ~E_NOTICE • in runtime error_reporting(E_ALL & ~E_NOTICE); • in .htaccess or apache.conf php_value error_reporting 6135 7| Sep 17, 2008 |
  • Handling the Errors There are four ways to handle errors • Display them • Log them • Ignore them • Act on them 8| Sep 17, 2008 |
  • Displaying Errors How to display errors in the standard output - • Set the display_errors directive to On • Set the error_reporting to the appropriate severity level Displaying errors is good for the programmer, bad for the user 9| Sep 17, 2008 |
  • Displaying Errors (cont) 10 | Sep 17, 2008 |
  • Displaying Errors (cont) 11 | Sep 17, 2008 |
  • Logging Errors How to set PHP to automatically log errors • Set the log_errors directive to On • Set the error_log directive to your preferred logging option PHP supports two options for logging errors • Logging to a file – set the error_log to a file path • Logging to syslog – set the error_log to syslog 12 | Sep 17, 2008 |
  • Ignoring Errors Don't do that. 13 | Sep 17, 2008 |
  • Acting on Errors PHP enables us to set a default error handler using the set_error_handler() function Five parameters will be passed to the user-defined error handler function • integer $errno – error severity level • string $errstr – error message • string $errfile [optional] – filename where the error was raised • integer $errline [optional] – line number where the error was raised • array $errcontext [optional] - an array of every variable that existed in the scope the error was triggered in 14 | Sep 17, 2008 |
  • Acting on Errors (cont) function demoErrorHandler($errno, $errstr, $errfile, $errline) { switch ($errno) { case E_USER_ERROR: Logger::log(E_ERROR, $errstr, $errfile, $errline); require_once(FULL_PATH_DEFAULT_ERROR_PAGE); exit(1); // control the flow break; case E_WARNING: case E_USER_WARNING: Logger::log(E_WARNING, $errstr, $errfile, $errline); break; case E_NOTICE: case E_USER_NOTICE: Logger::log(E_NOTICE, $errstr, $errfile, $errline); break; default: Logger::log(0, $errstr, $errfile, $errline); break; } return true; // Avoid running PHP's internal error handler } set_error_handler(quot;demoErrorHandlerquot;); 15 | Sep 17, 2008 |
  • Acting on Errors (cont) What can the error handler do? • Display a safer message to the user • Insert the data into a DB • Write to a file • Send an email • ... Keep in mind that on nonfatal errors, your script will keep on running 16 | Sep 17, 2008 |
  • Handling External Errors External errors will always occur at some point of an application's life-cycle External errors which are not accounted for are bugs for example: • Assuming a DB connection always succeeds Assumption is the big • Assuming a file is opened mama of all.... properly • Assuming an XML file has the right format • ... 17 | Sep 17, 2008 |
  • Handling External Errors (cont) $fh = @fopen($myfile, 'w'); $fh ->fwrite('save the rhinos!'); $fh = fopen($myfile, 'w'); if ($fh) { $fh­>write('save the rhinos!'); } else { redirectToErrorPage('Failed opening an important file'); die(1); } $db = mysql_connect(); mysql_query('SELECT * FROM users WHERE id=18'); $db = mysql_connect(); if (! $db) { redirectToErrorPage('Could not connect to the database!'); die(1); } mysql_query('SELECT * FROM users WHERE id=18', $db); 18 | Sep 17, 2008 |
  • Zend Monitor 19 | Sep 17, 2008 |
  • Exceptions An Exception can be thought of as a flow-control structure, or as an error control mechanism • Exceptions should be used to handle logic errors • Exceptions may be considered as any other type of flow- control syntax (such as if-else, while and foreach) • Exceptions are slower and consume more memory than other flow-control syntaxes, therefore it is not recommended to use it as a flow-control structure per se Unhandled Exceptions are fatal errors 20 | Sep 17, 2008 |
  • Exceptions (cont) 21 | Sep 17, 2008 |
  • Exceptions (cont) Exceptions are classes and therefore you may extend them to fit your needs or serve as markers class DataBaseException extends Exception { } class MathException extends Exception { } 22 | Sep 17, 2008 |
  • Handling Exceptions Terminology: • throw – the act of publishing an Exception • try block – a segment of the code which may have an exception thrown in it • catch block – a segment of the code which handles an exception if one happens • finally – is not available in PHP, but common in other languages 23 | Sep 17, 2008 |
  • Handling Exceptions (cont) try { if (0 == $denominator) { throw new Exception('Zero denominator'); } echo ($numerator / $denominator);   } catch (Exception $e) { echo 'You can not divide by zero'; die; // make sure the script stops } 24 | Sep 17, 2008 |
  • Handling Errors (cont) class Calculator { /**  * @param float $numerator  * @param float $denominator  * @return float  * @throws MathException  */ function divide($numerator, $denominator) { if (0 == $denominator) { throw new MathException('Zero denominator'); } return ($numerator / $denominator); } } 25 | Sep 17, 2008 |
  • Handling Exceptions (cont) It is possible to have several catch block for one try block where each is intended to catch a different type of Exception try { $calc = new Calculator(); echo $calc­>divide($numerator, $denominator); } catch (MathException $e) { echo 'A mathematic integrity failure: ', $e­>getMessage(); } catch (Exception $e) { echo 'A system error: ', $e­>getMessage() } echo 'Done'; 26 | Sep 17, 2008 |
  • Exception Hierarchies Since Exceptions are objects, i.e. instances of classes, you should take advantage of class hierarchy capabilities e.g. have Db2Exception, MysqlException etc. extend DataBaseException try { $user = new User($username); $user­>authenticate($password); $user­>getAccountBalance(); } catch (UserAuthenticationException $e) { echo quot;The user is not logged inquot;; } catch (DataBaseException $e) { Logger::logException('DB Error', $e); echo quot;The system has encounter some internal errorquot;; } catch (Exception $e) { Logger::logException('Unknown error', $e); echo quot;The system has encounter some internal errorquot;; } 27 | Sep 17, 2008 |
  • Advanced Exceptions The basic Exception class is a written in C and most of its methods are defined as final Since it is a PHP class it may be extended to fit your needs. You may add functions and attributes to it You may only override its __toString() method 28 | Sep 17, 2008 |
  • Advanced Exceptions (cont) class MysqlException extends Exception { private $comment = 'Zend Conference 2008 Example'; private $backtrace; public function __construct() { $this­>code = mysql_errno();  $this­>message = mysql_error(); $this­>backtrace = debug_backtrace(); } public function __toString() { return 'Papa was a Rolling Stone'; } } try { if (! mysql_connect()) { throw new MysqlException(); } } catch (MysqlException $e) { echo $e->getMessage(); } catch (Exception $e) { // do something else } 29 | Sep 17, 2008 |
  • Cascading Exceptions Exceptions bubble up until they are caught in the first catch block which wraps them. As mentioned before, uncaught Exceptions are fatal errors Use this behavior to cascade Exceptions, i.e. catch them in a smaller logic frame and bubble only the needed data up 30 | Sep 17, 2008 |
  • Cascading Exceptions (cont) class User { public staticfunction fetch($username, $password) { try { $sql = quot;SELECT username FROM users WHERE “; $sql.= “ (username={$username} AND password={$password}) “; $sql.= “ LIMIT 1quot;; return (MysqlAdapter::fetch($sql)); } catch (DataBaseException $e) { Logger::logException('Db Error', $e); throw new UserExeption('Unable to authenticate the user'); } return false; } } try { $user = User::fetch('Eddo', 'karnaf'); } catch (Exception $e) { // redirect to an error page die; } 31 | Sep 17, 2008 |
  • Constructors PHP will always return an instance of the class when the constructor is called Throwing an exception in a constructor will enable us to distinguish between a successful construction and a failure If an Exception is called in a constructor, the destructor is not called 32 | Sep 17, 2008 |
  • Constructors (cont) class User { private $name; private $data; public function __construct($name) { $this­>name = (string)$name; $this­>data  = UserModel::getDataByName($name); if (empty($this­>data)) { throw new Exception(quot;The system failed for {$name}quot;); } } } try  { $user = new User('Eddo Rotman'); } catch (Exception $e) { throw new Exception('Could not find the user'); } 33 | Sep 17, 2008 |
  • Default Exception Handler This is a user-defined top-level Exception Handler which will handle any uncaught Exception Unlike a try-catch block, after handling an Exception with the default error handler, the script halts Keep in mind that the default exception handler can not catch all uncaught exceptions which may happen in your code 34 | Sep 17, 2008 |
  • Default Exception Handler function  myDefaultExceptionHandler($exception) { // do something about it } set_exception_handler('myDefaultExceptionHandler'); class  MyExcpetionHandling { public static function doSomething($exception) { // do something about it } } set_exception_handler(array('MyExcpetionHandling', 'doSomething')); 35 | Sep 17, 2008 |
  • Conclusions • Errors happen, but it doesn't mean they should be ignored • Watch out for external errors or they may turn to bugs • Use Exceptions to better handle errors and logic flaws • Use Exceptions to distinguish between different error cases • Have a default error handler and a default exception handler, even if you are sure that everything is covered 36 | Sep 17, 2008 |
  • Questions? 37 Sep 17, 2008 | |