Error handling in PHP

后端 未结 9 1692
长情又很酷
长情又很酷 2020-12-02 08:40

I\'m familiar with some of the basics, but what I would like to know more about is when and why error handling (including throwing exceptions) should be used in PHP, especia

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 09:06

    Roughly speaking, errors are a legacy in PHP, while exceptions are the modern way to treat errors. The simplest thing then, is to set up an error-handler, that throws an exception. That way all errors are converted to exceptions, and then you can simply deal with one error-handling scheme. The following code will convert errors to exceptions for you:

    function exceptions_error_handler($severity, $message, $filename, $lineno) {
      if (error_reporting() == 0) {
        return;
      }
      if (error_reporting() & $severity) {
        throw new ErrorException($message, 0, $severity, $filename, $lineno);
      }
    }
    set_error_handler('exceptions_error_handler');
    error_reporting(E_ALL ^ E_STRICT);
    

    There are a few cases though, where code is specifically designed to work with errors. For example, the schemaValidate method of DomDocument raises warnings, when validating a document. If you convert errors to exceptions, it will stop validating after the first failure. Some times this is what you want, but when validating a document, you might actually want all failures. In this case, you can temporarily install an error-handler, that collects the errors. Here's a small snippet, I've used for that purpose:

    class errorhandler_LoggingCaller {
      protected $errors = array();
      function call($callback, $arguments = array()) {
        set_error_handler(array($this, "onError"));
        $orig_error_reporting = error_reporting(E_ALL);
        try {
          $result = call_user_func_array($callback, $arguments);
        } catch (Exception $ex) {
          restore_error_handler();
          error_reporting($orig_error_reporting);
          throw $ex;
        }
        restore_error_handler();
        error_reporting($orig_error_reporting);
        return $result;
      }
      function onError($severity, $message, $file = null, $line = null) {
        $this->errors[] = $message;
      }
      function getErrors() {
        return $this->errors;
      }
      function hasErrors() {
        return count($this->errors) > 0;
      }
    }
    

    And a use case:

    $doc = new DomDocument();
    $doc->load($xml_filename);
    $validation = new errorhandler_LoggingCaller();
    $validation->call(
      array($doc, 'schemaValidate'),
      array($xsd_filename));
    if ($validation->hasErrors()) {
      var_dump($validation->getErrors());
    }
    

提交回复
热议问题