Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 do I have different error handlers for different types of errors?

like image 425
Zerbu Avatar asked Feb 09 '12 22:02

Zerbu


People also ask

What are different error handling methods in PHP?

We will show different error handling methods: Simple "die()" statements. Custom errors and error triggers. Error reporting.

What mechanisms does PHP provide for handling runtime errors?

Exception handling is a powerful mechanism of PHP, which is used to handle runtime errors (runtime errors are called exceptions). So that the normal flow of the application can be maintained. The main purpose of using exception handling is to maintain the normal execution of the application.

How many types of error are there in PHP?

PHP Errors: 4 Different Types (Warning, Parse, Fatal, and Notice Error)


2 Answers

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

switch($errno){
   case E_USER_ERROR: UserErrorHandler(...); break;
}
like image 96
adioe3 Avatar answered Sep 27 '22 18:09

adioe3


So, to latch on to what Westie is saying, the important part is you can only have one error handler, and the set_error_handler() function returns the previously defined error handler, or null if none were defined. So in your error handlers, possibly use a class that stores the previous error handler when registering it, so that when you handle errors with your class method, call the previous error handler as well. An excerpt from the raven-php Sentry 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 handle 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);
    }
}
like image 37
thorne51 Avatar answered Sep 27 '22 17:09

thorne51