Exceptions in PHP - Try/Catch or set_exception_handler?

后端 未结 3 1216
刺人心
刺人心 2020-12-23 10:29

I\'m developing some lower end code in my system that uses multiple child classes of the php exception class. Essentially I have the exceptions broken up to a few categorie

3条回答
  •  有刺的猬
    2020-12-23 11:16

    1. Run your web requests through a Front Controller script
    2. call set_exception_handler early in execution (don't forget to account for error_reporting()). set_exception_handler takes as its paramter what php calls a "callback". You can pass an object method like so:

      // $object->methodName() will be called on errors
      set_exception_handler(array($object, 'methodName'));
      
    3. Wrap your dispatching code with try/catch to catch any code that DOES throw exceptions. The catch part of your code will catch all your own codes' exceptions, plus some php errors that didn't generate an exception natively (eg fopen or something), thanks to your set_exception_handler call above. The php manual states:

      The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

    4. Log errors as necessary.

    5. Create an error page template (the "View") that operates on an Exception object (the "Model") and pretty prints the whole stack trace for you, in development. Create a different template that goes to production. Branch on your environment, for example:

      catch(Exception $e) {
          // log error as necessary here.
          if("in developement") {
              // $e would be available to your template at this point
              include "errortemplates/dev.php";
          } else {
              include "errortemplates/prod.php";
          }
      }
      

提交回复
热议问题