Tutorial :Try Catch with PHP warnings



Question:

Is it possible to do some sort of try catch that will catch warnings?

e.g.

if (!$dom->loadHTMLFile($url)) {      //if cant load file handle error my way  }  

For the $url I am using I am getting

Warning (2): DOMDocument::loadHTMLFile(MYURL) [domdocument.loadhtmlfile]: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden   [APP\controllers\import_controller.php, line 62]    Warning (2): DOMDocument::loadHTMLFile() [domdocument.loadhtmlfile]: I/O warning : failed to load external entity "hMYURL" [APP\controllers\import_controller.php, line 62]  

I could just suppress the error, and do something if the call returns false but I want to be able catch the exact warning message and then do something with it.

Is this possible?

Thanks


Solution:1

You should use libxml_use_internal_errors for this.

This example is adapted from the manual:

libxml_use_internal_errors(true);  $doc = new DOMDocument();  $res = $doc->loadHTMLFile($url); //this may fail and return FALSE!  foreach (libxml_get_errors() as $error) {      // handle errors here  }  libxml_clear_errors();  

No PHP notices will be emitted here.


Solution:2

Probably you are looking for this

<?php  // error handler function  function myErrorHandler($errno, $errstr, $errfile, $errline)  {      switch ($errno) {      case E_USER_ERROR:          echo "<b>My ERROR</b> [$errno] $errstr<br />\n";          echo "  Fatal error on line $errline in file $errfile";          echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";          echo "Aborting...<br />\n";          exit(1);          break;        case E_USER_WARNING:          echo "<b>My WARNING</b> [$errno] $errstr<br />\n";          break;        case E_USER_NOTICE:          echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";          break;        default:          echo "Unknown error type: [$errno] $errstr<br />\n";          break;      }        /* Don't execute PHP internal error handler */      return true;  }    // function to test the error handling  function scale_by_log($vect, $scale)  {      if (!is_numeric($scale) || $scale <= 0) {          trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);      }        if (!is_array($vect)) {          trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);          return null;      }        $temp = array();      foreach($vect as $pos => $value) {          if (!is_numeric($value)) {              trigger_error("Value at position $pos is not a number, using 0 (zero)", E_USER_NOTICE);              $value = 0;          }          $temp[$pos] = log($scale) * $value;      }        return $temp;  }    // set to the user defined error handler  $old_error_handler = set_error_handler("myErrorHandler");    // trigger some errors, first define a mixed array with a non-numeric item  echo "vector a\n";  $a = array(2, 3, "foo", 5.5, 43.3, 21.11);  print_r($a);    // now generate second array  echo "----\nvector b - a notice (b = log(PI) * a)\n";  /* Value at position $pos is not a number, using 0 (zero) */  $b = scale_by_log($a, M_PI);  print_r($b);    // this is trouble, we pass a string instead of an array  echo "----\nvector c - a warning\n";  /* Incorrect input vector, array of values expected */  $c = scale_by_log("not array", 2.3);  var_dump($c); // NULL    // this is a critical error, log of zero or negative number is undefined  echo "----\nvector d - fatal error\n";  /* log(x) for x <= 0 is undefined, you used: scale = $scale" */  $d = scale_by_log($a, -2.5);  var_dump($d); // Never reached  ?>  

this will make this output:

vector a  Array  (      [0] => 2      [1] => 3      [2] => foo      [3] => 5.5      [4] => 43.3      [5] => 21.11  )  ----  vector b - a notice (b = log(PI) * a)  <b>My NOTICE</b> [1024] Value at position 2 is not a number, using 0 (zero)<br />  Array  (      [0] => 2.2894597716988      [1] => 3.4341896575482      [2] => 0      [3] => 6.2960143721717      [4] => 49.566804057279      [5] => 24.165247890281  )  ----  vector c - a warning  <b>My WARNING</b> [512] Incorrect input vector, array of values expected<br />  NULL  ----  vector d - fatal error  <b>My ERROR</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br />    Fatal error on line 35 in file trigger_error.php, PHP 5.2.1 (FreeBSD)<br />  Aborting...<br />  

Read more


Solution:3

You might be able to use a custom error handler but I am not completely sure if the warnings you get can be handled. Some errors or warnings will always use the default error handler. But just try it out.


Solution:4

I just found a very attractive solution at http://bytes.com/topic/php/answers/6296-catch-warnings:

First tell PHP to track all errors:

ini_set('track_errors', '1');  

This puts all error messages (incl. warnings) into the variable $php_errormsg (see http://www.php.net/manual/en/errorfunc.configuration.php#ini.track-errors).

Then you can catch errors and warnings like this:

if (!@copy('no_file', 'some_file')) {    echo $php_errormsg, "\n";  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »