SlideShare une entreprise Scribd logo
1  sur  37
Télécharger pour lire hors ligne
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 |
 |

Contenu connexe

Tendances

Perl exceptions lightning talk
Perl exceptions lightning talkPerl exceptions lightning talk
Perl exceptions lightning talkPeter Edwards
 
Methods of debugging - Atomate.net
Methods of debugging - Atomate.netMethods of debugging - Atomate.net
Methods of debugging - Atomate.netVitalie Chiperi
 
PHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet SolutionPHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet SolutionMazenetsolution
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPwahidullah mudaser
 
Errors, Exceptions & Logging (PHPNW13 Uncon)
Errors, Exceptions & Logging (PHPNW13 Uncon)Errors, Exceptions & Logging (PHPNW13 Uncon)
Errors, Exceptions & Logging (PHPNW13 Uncon)James Titcumb
 
Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)Sharon Levy
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requireTheCreativedev Blog
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operatorsKhem Puthea
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboardsDenis Ristic
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...anshkhurana01
 
Php(report)
Php(report)Php(report)
Php(report)Yhannah
 

Tendances (20)

Perl exceptions lightning talk
Perl exceptions lightning talkPerl exceptions lightning talk
Perl exceptions lightning talk
 
Methods of debugging - Atomate.net
Methods of debugging - Atomate.netMethods of debugging - Atomate.net
Methods of debugging - Atomate.net
 
PHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet SolutionPHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet Solution
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Errors, Exceptions & Logging (PHPNW13 Uncon)
Errors, Exceptions & Logging (PHPNW13 Uncon)Errors, Exceptions & Logging (PHPNW13 Uncon)
Errors, Exceptions & Logging (PHPNW13 Uncon)
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)
 
Data Types In PHP
Data Types In PHPData Types In PHP
Data Types In PHP
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operators
 
Lesson 4 constant
Lesson 4  constantLesson 4  constant
Lesson 4 constant
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
 
Php(report)
Php(report)Php(report)
Php(report)
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 
PHP 5.3
PHP 5.3PHP 5.3
PHP 5.3
 
Bioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-filesBioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-files
 
Operators php
Operators phpOperators php
Operators php
 

En vedette

Developing highly scalable applications with Symfony and RabbitMQ
Developing highly scalable applications with  Symfony and RabbitMQDeveloping highly scalable applications with  Symfony and RabbitMQ
Developing highly scalable applications with Symfony and RabbitMQAlexey Petrov
 
Orchestrating Docker in production - TIAD Camp Docker
Orchestrating Docker in production - TIAD Camp DockerOrchestrating Docker in production - TIAD Camp Docker
Orchestrating Docker in production - TIAD Camp DockerThe Incredible Automation Day
 
Software Architectures, Week 3 - Microservice-based Architectures
Software Architectures, Week 3 - Microservice-based ArchitecturesSoftware Architectures, Week 3 - Microservice-based Architectures
Software Architectures, Week 3 - Microservice-based ArchitecturesAngelos Kapsimanis
 
Astricon 2016 - Scaling ARI and Production
Astricon 2016 - Scaling ARI and ProductionAstricon 2016 - Scaling ARI and Production
Astricon 2016 - Scaling ARI and ProductionDan Jenkins
 
Chicago AWS user group meetup - May 2014 at Cohesive
Chicago AWS user group meetup - May 2014 at CohesiveChicago AWS user group meetup - May 2014 at Cohesive
Chicago AWS user group meetup - May 2014 at CohesiveAWS Chicago
 
Automated Infrastructure Security: Monitoring using FOSS
Automated Infrastructure Security: Monitoring using FOSSAutomated Infrastructure Security: Monitoring using FOSS
Automated Infrastructure Security: Monitoring using FOSSSonatype
 
Choosing the right data storage in the Cloud.
Choosing the right data storage in the Cloud. Choosing the right data storage in the Cloud.
Choosing the right data storage in the Cloud. Amazon Web Services
 
Gaurav dev ops (AWS, Linux, Automation-ansible, jenkins:CI and CD:Ansible)
Gaurav dev ops (AWS, Linux, Automation-ansible, jenkins:CI and CD:Ansible)Gaurav dev ops (AWS, Linux, Automation-ansible, jenkins:CI and CD:Ansible)
Gaurav dev ops (AWS, Linux, Automation-ansible, jenkins:CI and CD:Ansible)Gaurav Srivastav
 
Bridging the Gap: Connecting AWS and Kafka
Bridging the Gap: Connecting AWS and KafkaBridging the Gap: Connecting AWS and Kafka
Bridging the Gap: Connecting AWS and KafkaPengfei (Jason) Li
 
Reactive Cloud Security | AWS Public Sector Summit 2016
Reactive Cloud Security | AWS Public Sector Summit 2016Reactive Cloud Security | AWS Public Sector Summit 2016
Reactive Cloud Security | AWS Public Sector Summit 2016Amazon Web Services
 
Docker for PHP Developers - Madison PHP 2017
Docker for PHP Developers - Madison PHP 2017Docker for PHP Developers - Madison PHP 2017
Docker for PHP Developers - Madison PHP 2017Chris Tankersley
 
MyHeritage backend group - build to scale
MyHeritage backend group - build to scaleMyHeritage backend group - build to scale
MyHeritage backend group - build to scaleRan Levy
 
Python Pants Build System for Large Codebases
Python Pants Build System for Large CodebasesPython Pants Build System for Large Codebases
Python Pants Build System for Large CodebasesAngad Singh
 
Platform - Technical architecture
Platform - Technical architecturePlatform - Technical architecture
Platform - Technical architectureDavid Rundle
 
Application Deployment at UC Riverside
Application Deployment at UC RiversideApplication Deployment at UC Riverside
Application Deployment at UC RiversideMichael Kennedy
 

En vedette (20)

Developing highly scalable applications with Symfony and RabbitMQ
Developing highly scalable applications with  Symfony and RabbitMQDeveloping highly scalable applications with  Symfony and RabbitMQ
Developing highly scalable applications with Symfony and RabbitMQ
 
Orchestrating Docker in production - TIAD Camp Docker
Orchestrating Docker in production - TIAD Camp DockerOrchestrating Docker in production - TIAD Camp Docker
Orchestrating Docker in production - TIAD Camp Docker
 
Software Architectures, Week 3 - Microservice-based Architectures
Software Architectures, Week 3 - Microservice-based ArchitecturesSoftware Architectures, Week 3 - Microservice-based Architectures
Software Architectures, Week 3 - Microservice-based Architectures
 
Astricon 2016 - Scaling ARI and Production
Astricon 2016 - Scaling ARI and ProductionAstricon 2016 - Scaling ARI and Production
Astricon 2016 - Scaling ARI and Production
 
Yirgacheffe Chelelelktu Washed Coffee 2015
Yirgacheffe Chelelelktu Washed Coffee 2015Yirgacheffe Chelelelktu Washed Coffee 2015
Yirgacheffe Chelelelktu Washed Coffee 2015
 
Chicago AWS user group meetup - May 2014 at Cohesive
Chicago AWS user group meetup - May 2014 at CohesiveChicago AWS user group meetup - May 2014 at Cohesive
Chicago AWS user group meetup - May 2014 at Cohesive
 
Automated Infrastructure Security: Monitoring using FOSS
Automated Infrastructure Security: Monitoring using FOSSAutomated Infrastructure Security: Monitoring using FOSS
Automated Infrastructure Security: Monitoring using FOSS
 
ITV& Bashton
ITV& Bashton ITV& Bashton
ITV& Bashton
 
Choosing the right data storage in the Cloud.
Choosing the right data storage in the Cloud. Choosing the right data storage in the Cloud.
Choosing the right data storage in the Cloud.
 
Gaurav dev ops (AWS, Linux, Automation-ansible, jenkins:CI and CD:Ansible)
Gaurav dev ops (AWS, Linux, Automation-ansible, jenkins:CI and CD:Ansible)Gaurav dev ops (AWS, Linux, Automation-ansible, jenkins:CI and CD:Ansible)
Gaurav dev ops (AWS, Linux, Automation-ansible, jenkins:CI and CD:Ansible)
 
Jake Fox Pd. 5
Jake Fox Pd. 5Jake Fox Pd. 5
Jake Fox Pd. 5
 
Linux Malware Analysis
Linux Malware Analysis	Linux Malware Analysis
Linux Malware Analysis
 
Bridging the Gap: Connecting AWS and Kafka
Bridging the Gap: Connecting AWS and KafkaBridging the Gap: Connecting AWS and Kafka
Bridging the Gap: Connecting AWS and Kafka
 
Reactive Cloud Security | AWS Public Sector Summit 2016
Reactive Cloud Security | AWS Public Sector Summit 2016Reactive Cloud Security | AWS Public Sector Summit 2016
Reactive Cloud Security | AWS Public Sector Summit 2016
 
Docker for PHP Developers - Madison PHP 2017
Docker for PHP Developers - Madison PHP 2017Docker for PHP Developers - Madison PHP 2017
Docker for PHP Developers - Madison PHP 2017
 
MyHeritage backend group - build to scale
MyHeritage backend group - build to scaleMyHeritage backend group - build to scale
MyHeritage backend group - build to scale
 
Python Pants Build System for Large Codebases
Python Pants Build System for Large CodebasesPython Pants Build System for Large Codebases
Python Pants Build System for Large Codebases
 
Platform - Technical architecture
Platform - Technical architecturePlatform - Technical architecture
Platform - Technical architecture
 
Application Deployment at UC Riverside
Application Deployment at UC RiversideApplication Deployment at UC Riverside
Application Deployment at UC Riverside
 
Kelompok 2
Kelompok 2Kelompok 2
Kelompok 2
 

Similaire à Elegant Ways of Handling PHP Errors and Exceptions

Webinar PHParty7 - Errors handlings
Webinar PHParty7 - Errors handlingsWebinar PHParty7 - Errors handlings
Webinar PHParty7 - Errors handlingsDarkmira
 
Server Independent Programming
Server Independent ProgrammingServer Independent Programming
Server Independent ProgrammingZendCon
 
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)James Titcumb
 
Lesser Known Security Problems in PHP Applications
Lesser Known Security Problems in PHP ApplicationsLesser Known Security Problems in PHP Applications
Lesser Known Security Problems in PHP ApplicationsZendCon
 
lecture 15.pptx
lecture 15.pptxlecture 15.pptx
lecture 15.pptxITNet
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsRandy Connolly
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 TrainingChris Chubb
 
Error handling in XPages
Error handling in XPagesError handling in XPages
Error handling in XPagesdominion
 
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)James Titcumb
 
Error management
Error managementError management
Error managementdaniil3
 
A exception ekon16
A exception ekon16A exception ekon16
A exception ekon16Max Kleiner
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Angelin R
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterZendCon
 
Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]ppd1961
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?Christophe Porteneuve
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Jalpesh Vasa
 

Similaire à Elegant Ways of Handling PHP Errors and Exceptions (20)

Webinar PHParty7 - Errors handlings
Webinar PHParty7 - Errors handlingsWebinar PHParty7 - Errors handlings
Webinar PHParty7 - Errors handlings
 
Server Independent Programming
Server Independent ProgrammingServer Independent Programming
Server Independent Programming
 
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
 
Lesser Known Security Problems in PHP Applications
Lesser Known Security Problems in PHP ApplicationsLesser Known Security Problems in PHP Applications
Lesser Known Security Problems in PHP Applications
 
lecture 15.pptx
lecture 15.pptxlecture 15.pptx
lecture 15.pptx
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 Training
 
Error handling in XPages
Error handling in XPagesError handling in XPages
Error handling in XPages
 
SPL, not a bridge too far
SPL, not a bridge too farSPL, not a bridge too far
SPL, not a bridge too far
 
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
 
Error management
Error managementError management
Error management
 
A exception ekon16
A exception ekon16A exception ekon16
A exception ekon16
 
Debugging With Php
Debugging With PhpDebugging With Php
Debugging With Php
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)
 
Exception handling
Exception handlingException handling
Exception handling
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
PHP 5.3/6
PHP 5.3/6PHP 5.3/6
PHP 5.3/6
 

Plus de ZendCon

Framework Shootout
Framework ShootoutFramework Shootout
Framework ShootoutZendCon
 
Zend_Tool: Practical use and Extending
Zend_Tool: Practical use and ExtendingZend_Tool: Practical use and Extending
Zend_Tool: Practical use and ExtendingZendCon
 
PHP on IBM i Tutorial
PHP on IBM i TutorialPHP on IBM i Tutorial
PHP on IBM i TutorialZendCon
 
PHP on Windows - What's New
PHP on Windows - What's NewPHP on Windows - What's New
PHP on Windows - What's NewZendCon
 
PHP and Platform Independance in the Cloud
PHP and Platform Independance in the CloudPHP and Platform Independance in the Cloud
PHP and Platform Independance in the CloudZendCon
 
I18n with PHP 5.3
I18n with PHP 5.3I18n with PHP 5.3
I18n with PHP 5.3ZendCon
 
Cloud Computing: The Hard Problems Never Go Away
Cloud Computing: The Hard Problems Never Go AwayCloud Computing: The Hard Problems Never Go Away
Cloud Computing: The Hard Problems Never Go AwayZendCon
 
Planning for Synchronization with Browser-Local Databases
Planning for Synchronization with Browser-Local DatabasesPlanning for Synchronization with Browser-Local Databases
Planning for Synchronization with Browser-Local DatabasesZendCon
 
Magento - a Zend Framework Application
Magento - a Zend Framework ApplicationMagento - a Zend Framework Application
Magento - a Zend Framework ApplicationZendCon
 
Enterprise-Class PHP Security
Enterprise-Class PHP SecurityEnterprise-Class PHP Security
Enterprise-Class PHP SecurityZendCon
 
PHP and IBM i - Database Alternatives
PHP and IBM i - Database AlternativesPHP and IBM i - Database Alternatives
PHP and IBM i - Database AlternativesZendCon
 
Zend Core on IBM i - Security Considerations
Zend Core on IBM i - Security ConsiderationsZend Core on IBM i - Security Considerations
Zend Core on IBM i - Security ConsiderationsZendCon
 
Application Diagnosis with Zend Server Tracing
Application Diagnosis with Zend Server TracingApplication Diagnosis with Zend Server Tracing
Application Diagnosis with Zend Server TracingZendCon
 
Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP A...
Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP A...Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP A...
Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP A...ZendCon
 
Solving the C20K problem: Raising the bar in PHP Performance and Scalability
Solving the C20K problem: Raising the bar in PHP Performance and ScalabilitySolving the C20K problem: Raising the bar in PHP Performance and Scalability
Solving the C20K problem: Raising the bar in PHP Performance and ScalabilityZendCon
 
Joe Staner Zend Con 2008
Joe Staner Zend Con 2008Joe Staner Zend Con 2008
Joe Staner Zend Con 2008ZendCon
 
Tiery Eyed
Tiery EyedTiery Eyed
Tiery EyedZendCon
 
Make your PHP Application Software-as-a-Service (SaaS) Ready with the Paralle...
Make your PHP Application Software-as-a-Service (SaaS) Ready with the Paralle...Make your PHP Application Software-as-a-Service (SaaS) Ready with the Paralle...
Make your PHP Application Software-as-a-Service (SaaS) Ready with the Paralle...ZendCon
 
DB2 Storage Engine for MySQL and Open Source Applications Session
DB2 Storage Engine for MySQL and Open Source Applications SessionDB2 Storage Engine for MySQL and Open Source Applications Session
DB2 Storage Engine for MySQL and Open Source Applications SessionZendCon
 
Digital Identity
Digital IdentityDigital Identity
Digital IdentityZendCon
 

Plus de ZendCon (20)

Framework Shootout
Framework ShootoutFramework Shootout
Framework Shootout
 
Zend_Tool: Practical use and Extending
Zend_Tool: Practical use and ExtendingZend_Tool: Practical use and Extending
Zend_Tool: Practical use and Extending
 
PHP on IBM i Tutorial
PHP on IBM i TutorialPHP on IBM i Tutorial
PHP on IBM i Tutorial
 
PHP on Windows - What's New
PHP on Windows - What's NewPHP on Windows - What's New
PHP on Windows - What's New
 
PHP and Platform Independance in the Cloud
PHP and Platform Independance in the CloudPHP and Platform Independance in the Cloud
PHP and Platform Independance in the Cloud
 
I18n with PHP 5.3
I18n with PHP 5.3I18n with PHP 5.3
I18n with PHP 5.3
 
Cloud Computing: The Hard Problems Never Go Away
Cloud Computing: The Hard Problems Never Go AwayCloud Computing: The Hard Problems Never Go Away
Cloud Computing: The Hard Problems Never Go Away
 
Planning for Synchronization with Browser-Local Databases
Planning for Synchronization with Browser-Local DatabasesPlanning for Synchronization with Browser-Local Databases
Planning for Synchronization with Browser-Local Databases
 
Magento - a Zend Framework Application
Magento - a Zend Framework ApplicationMagento - a Zend Framework Application
Magento - a Zend Framework Application
 
Enterprise-Class PHP Security
Enterprise-Class PHP SecurityEnterprise-Class PHP Security
Enterprise-Class PHP Security
 
PHP and IBM i - Database Alternatives
PHP and IBM i - Database AlternativesPHP and IBM i - Database Alternatives
PHP and IBM i - Database Alternatives
 
Zend Core on IBM i - Security Considerations
Zend Core on IBM i - Security ConsiderationsZend Core on IBM i - Security Considerations
Zend Core on IBM i - Security Considerations
 
Application Diagnosis with Zend Server Tracing
Application Diagnosis with Zend Server TracingApplication Diagnosis with Zend Server Tracing
Application Diagnosis with Zend Server Tracing
 
Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP A...
Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP A...Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP A...
Insights from the Experts: How PHP Leaders Are Transforming High-Impact PHP A...
 
Solving the C20K problem: Raising the bar in PHP Performance and Scalability
Solving the C20K problem: Raising the bar in PHP Performance and ScalabilitySolving the C20K problem: Raising the bar in PHP Performance and Scalability
Solving the C20K problem: Raising the bar in PHP Performance and Scalability
 
Joe Staner Zend Con 2008
Joe Staner Zend Con 2008Joe Staner Zend Con 2008
Joe Staner Zend Con 2008
 
Tiery Eyed
Tiery EyedTiery Eyed
Tiery Eyed
 
Make your PHP Application Software-as-a-Service (SaaS) Ready with the Paralle...
Make your PHP Application Software-as-a-Service (SaaS) Ready with the Paralle...Make your PHP Application Software-as-a-Service (SaaS) Ready with the Paralle...
Make your PHP Application Software-as-a-Service (SaaS) Ready with the Paralle...
 
DB2 Storage Engine for MySQL and Open Source Applications Session
DB2 Storage Engine for MySQL and Open Source Applications SessionDB2 Storage Engine for MySQL and Open Source Applications Session
DB2 Storage Engine for MySQL and Open Source Applications Session
 
Digital Identity
Digital IdentityDigital Identity
Digital Identity
 

Dernier

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Dernier (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

Elegant Ways of Handling PHP Errors and Exceptions

  • 1. ELEGANT WAYS OF HANDLING PHP ERRORS AND EXCEPTIONS By Eddo Rotman   Copyright © 2008, Zend Technologies Inc.
  • 2. 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 |
  • 3. 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 |
  • 4. 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 |
  • 5. 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 |
  • 6. 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 |
  • 7. 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 |
  • 8. Handling the Errors There are four ways to handle errors • Display them • Log them • Ignore them • Act on them 8| Sep 17, 2008 |
  • 9. 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 |
  • 10. Displaying Errors (cont) 10 | Sep 17, 2008 |
  • 11. Displaying Errors (cont) 11 | Sep 17, 2008 |
  • 12. 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 |
  • 13. Ignoring Errors Don't do that. 13 | Sep 17, 2008 |
  • 14. 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 |
  • 15. 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 |
  • 16. 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 |
  • 17. 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 |
  • 18. 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 |
  • 19. Zend Monitor 19 | Sep 17, 2008 |
  • 20. 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 |
  • 21. Exceptions (cont) 21 | Sep 17, 2008 |
  • 22. 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 |
  • 23. 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 |
  • 24. 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 |
  • 25. 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 |
  • 26. 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 |
  • 27. 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 |
  • 28. 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 |
  • 29. 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 |
  • 30. 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 |
  • 31. 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 |
  • 32. 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 |
  • 33. 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 |
  • 34. 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 |
  • 35. 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 |
  • 36. 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 |