How do you get multiple error handlers in PHP?

I tried this:

set_error_handler('ReportError', E_NOTICE | E_USER_NOTICE); set_error_handler('ErrorHandler', E_ALL & ~(E_NOTICE | E_USER_NOTICE)); 

But only the second one works. How can I use different error handlers for different types of errors?

+6
source share
3 answers

Why not process one error handler and filter by the type of errors in the handler and call different functions from there? Make GenericErrorHandler() and do it in it:

 switch($errno){ case E_USER_ERROR: UserErrorHandler(...); break; } 
+5
source

So, to consolidate what Westie says, the important part is that you can have only one error handler, and the set_error_handler () function returns the previously defined error handler or null if none are defined. Therefore, in error handlers, perhaps use the class that stores the previous error handler when registering it, so when you handle errors using the class method, call the previous error handler. Excerpt from raven-php chat client:

  public function registerErrorHandler($call_existing_error_handler = true, $error_types = -1) { $this->error_types = $error_types; $this->old_error_handler = set_error_handler(array($this, 'handleError'), error_reporting()); $this->call_existing_error_handler = $call_existing_error_handler; } 

and then the descriptor error method:

  public function handleError($code, $message, $file = '', $line = 0, $context=array()) { if ($this->error_types & $code & error_reporting()) { $e = new ErrorException($message, 0, $code, $file, $line); $this->handleException($e, true, $context); } if ($this->call_existing_error_handler && $this->old_error_handler) { call_user_func($this->old_error_handler, $code, $message, $file, $line, $context); } } 
+3
source

You can have one error handler and handle such errors (well, this is PHP 5.3, but excuse me - small changes and it will work fine)

 set_error_handler(function($errno, $errstr, $errfile, $errline) { switch($errno) { case E_ERROR: { # Bla bla bla, your code here return true; } } return false; }); 

If you really have to use two different set_error_handler, you can use the function call to get the previous error handler. And even then you lose those errors that you filter.

The presence of such a controller, although much more elegant.

+1
source

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


All Articles