📜 ⬆️ ⬇️

PHP_Exceptionizer: E_NOTICE conversion to exceptions (Exception)

A very simple but useful library PHP_Exceptionizer allows you to convert notices (E_NOTICE), warnings (E_WARNING), etc. into PHP exceptions.

 // Somewhere in the initial script initialization code.
 error_reporting (E_ALL);
 if (<is debug mode active>) {
     $ exceptionizer = new PHP_Exceptionizer (E_ALL);
     // And leave this variable so that it will not be deleted until the end 
     // script.  Deleting a variable will disable the PHP_Exceptionizer.
 }
 ...
 // Then you can catch notes as exceptions:
 try {
     echo $ undefinedVariable;
 } catch (E_NOTICE $ e) {
     echo "Notice raised:".  $ e-> getMessage ();
 }
 ...
 // If you catch E_WARNING, then catch E_NOTICE too:
 try {
     echo $ undefinedVariable;
 } catch (E_WARNING $ e) {
     echo "Warning or better raised:".  $ e-> getMessage ();
 }
 ...
 // And you can not catch, then the notice will cause the end of the program.
 echo $ undefinedVariable;


The library is convenient to use when developing and debugging. As you know, it is better to carry it out in error_reporting = E_ALL mode and keeping in mind that even the smallest notice during development is a hint of a fatal error.

A typical example when notes can be lost is scripts that generate a redirect to another page. This occurs when output stream buffering is enabled (ob_start ()).
')
Of course, on the “combat” server it is better not to convert notices into exceptions (in order not to make an elephant out of a fly), but simply to read them in log files.

However, there is a case when it makes sense to include the library also in production mode. This is a mailing system. Imagine that you have written a script that sends letters to several millions of site subscribers, and the text of the letter is generated dynamically, depending on the profile of the user or his friends. You can catch yourself thinking that it is very scary to run this script ... Suddenly, there will be some kind of mistake, and a million people will see empty fields or a “crumpled” letter? PHP_Exceptionizer allows you to significantly reduce this risk if you turn it on at the time of generating the letter.

Download the library here: dklab.ru/lib/PHP_Exceptionizer

Source: https://habr.com/ru/post/55846/


All Articles