Handling errors

There are two ways to handle errors:

  • Handle them as return values of the methods
  • Handle them with a global error handler

Handling errors locally

If you want to handle errors, where they occur, you only need to check, whether the method returned an error object. This can be done using the patErrorManager::isError() method:

$file = new FileReader('/etc/passwd');
$result = $file->open();
if (patErrorManager::isError($result)) {
    echo "Error opening the file:\n";
    echo $result->getMessage();
}

Of course, this works only, if the called method actually returns the error object. If you take a look at the implementation of the open() method, you will remember, that we also raised a notice, that is not returned.

Setting an error handler

The patErrorManager class provides the static setErrorHandling() method which enables you to define, how all errors, warnings or notices are treated. The folloing error handling methods are available:

  • ignore : does nothing, when an error occures
  • echo : displays the error message and continues with the application
  • verbose : displays the error message and additional information and continues with the application
  • die : displays the error message and stops script execution
  • trigger : triggers a PHP error using trigger_error()
  • echo : displays the error message and continues with the application
  • exception : throws an exception (only available in PHP5)
  • callback : calls any method or function you provide

The setErrorHandling() method accepts the following arguments:

  • $errorLevel (E_ERROR, E_WARNING or E_NOTICE)
  • $handling (see list above)
  • $options (optional options for the mode)

The only mode, that currently accepts any options is the callback mode. In this case you need to pass the callback itself as the third argument.

Now let us take a look at some examples:

$handlerObject = new MyHandlerObject();

patErrorManager::setErrorHandling(E_ERROR, 'callback', array($handlerObject, 'handlerFunction'));
patErrorManager::setErrorHandling(E_WARNING, 'verbose');
patErrorManager::setErrorHandling(E_NOTICE, 'ignore');

Any errors will be passed to the handlerFunction() method of the $handlerObject. All warnings will be displayed and all notices will be ignored.

It is also possible to set the error-handling for more than one mode at once. The following example sets the mode for errors and warnings to die.

patErrorManager::setErrorHandling(E_WARNING|E_ERROR, 'die');

The patError-distribution already includes the patErrorHandlerDebug class, which can be used to generate nice error messages while debugging your applications. It also includes several examples that illustrate the use of setErrorHandling().