khernik khernik - 1 month ago 7
PHP Question

Converting PHP errors into exceptions

I've written error handling class which divided all errors into the normal ones (notices, warnings, ...), and the critical ones.

Now I've found out that it's a good practice to convert all errors into exceptions. It would also shorten my code.

However, I'm not sure how to handle this...


  1. Are there exceptions that don't stop scripts execution, and exceptions that do? If there aren't...how to differ converted errors?

  2. Converting errors into exception is done by calling set_error_handler() and throw new ErrorException() in there...What's next? set_exception_handler() is called automagically?


Answer
  1. Are there exceptions that don't stop scripts execution, and exceptions that do? If there aren't...how to differ converted errors?

Exceptions don't stop script execution if they're caught. To recognize a converted error:

try {
    // ...
} catch (ErrorException $e) {
    // converted error (probably)
} catch (Exception $e) {
    // another kind of exception; this basically catches all
}

Or:

function handle_exception(Exception $e)
{
    if ($e instanceof ErrorException) {
        // converted error (probably)
    } else {
        // another kind of exception
    }
}
set_exception_handler('handle_exception');

Note that ErrorException can be thrown by any piece of code, but it was meant to convert regular errors in set_error_handler() registered functions only.

  1. Converting errors into exception is done by calling set_error_handler() and throw new ErrorException() in there...What's next? set_exception_handler() is called automagically?

If the thrown ErrorException from your error handler function is not caught anywhere else in your code, the registered exception handler (set using set_exception_handler()) will be called.

Comments