26

I already set my error handler:

set_error_handler (function($errno, $errstr, $errfile,  $errline, array $errcontext) {
  $s = date('Ymd_His');
  switch ($errno)
  {
    case E_USER_ERROR:
      $s.= '_E_';
      break;
    case E_USER_WARNING:
      $s.= '_W_';
      break;
    case E_USER_NOTICE:
      $s.= '_N_';
      break;
    default:
      $s.= '_U_';
      break;
    }
    file_put_contents (APP_PATH_CACHE.'/log'.$s.'_'.rand(1,99999).'.html', print_r(get_defined_vars(), true));
}, E_ALL);

but can it be turn into an exception? So that I could see the flow.

John Smith
  • 6,129
  • 12
  • 68
  • 123
  • 2
    I don't understand the downvotes. Duplicated from question [10520390](http://stackoverflow.com/questions/10520390/stop-script-execution-upon-notice-warning)? Anyway, upvoting... – felipsmartins Sep 28 '15 at 12:21
  • 1
    well, to me it wasnt straightforward. If I throw just an exception, the backtrace will lead into the error handler, not the source of it. Similar problem with "fatal errors" in "shutdown" – John Smith Sep 28 '15 at 14:39
  • 1
    @JohnSmith the backtrace does cross the error handler location indeed, but it doesn't stop there, it continues to the line where the error was generated, see https://3v4l.org/CpsPS , they all mention line 13, where the error was generated. (since at least php 5.1, but probably earlier, but cba testing because ErrorException was introduced in 5.1) – hanshenrik May 27 '18 at 10:48

2 Answers2

35

Yes. this is exactly why the ErrorException was created. see http://php.net/manual/en/class.errorexception.php

function exception_error_handler($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting
        return;
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler("exception_error_handler");
hanshenrik
  • 19,904
  • 4
  • 43
  • 89
1

Yes it can be simply done. Best way is to create your own class that extends from \Exception and in your error_handler() throw object of this new class.

You can do it also in simple way after

file_put_contents (APP_PATH_CACHE.'/log'.$s.'_'.rand(1,99999).'.html', print_r(get_defined_vars(), true));

add

throw new Exception($errst, $errno); where first param is message and second is error number

Robert
  • 19,800
  • 5
  • 55
  • 85