Using PHP Exceptions
| Chapter 6. Error handling |

## Using PHP Exceptions

Starting with version v2.5 the library now have full support for PHP5 style exceptions. The library provides an exception class named `JpGraphException` which is slightly different compared with traditional exception classes in that this class can not only return an text string as error but also an image. This is necessary in order to handle the case where a script has an error and is called from within an <img> tag. The only data that can then be displayed in a browser is image data and hence it is necessary for the error to be formatted as an image.

In addition to providing an exception class the library also installs its own default exception handler to properly display an image. This default exception handler will be automatically called whenever an "uncaught" exception would otherwise be generated. This means that it is strictly not necessary to use "`try {} catch() {}`" blocks around the library scripts.

When an exception is generated the default exception handler first validates that the exception is a proper descendant of `JpGraphException` and if so, generates the image by calling the `JpgraphException::Stroke()` method. If the exception is not a `JpGraphException` based exception then the handler re-raises the error. This means that in script that you create that is meant to be called from within an <img> tag all exception should be a derivate of `JpGraphException` in order to properly generate an error image.

A typical example on how to raise an exception in your own code is shown in Example 6.1. Throwing a JpGraph exception

Example 6.1. Throwing a JpGraph exception

    1
    2
    3
    <?php
    throw new JpGraphException(' ... some error message ...');
    ?>

In case you need to handle the exception in a "`try {} catch() {}`" block (perhaps in order to do necessary cleanup) it is important to remember to call the `Stroke()` method which will create and stream the error message back to the browser. An example of this is shown in Example 6.2. Catching a JpGraph exception and sending it back as an image to the client

Example 6.2. Catching a JpGraph exception and sending it back as an image to the client

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <?php
    try {

        $graph = new Graph($width,$height);

        // ... Code to setup the graph

        if( /* some error condition */ ) {
            throw new JpGraphException(' ... some error message ...');
        }

    } catch ( JpGraphException $e ) {
        // .. do necessary cleanup

        // Send back error message
        $e->Stroke();
    }
    ?>

### Tip

Another typical augmentation of the exception handling might be to also log an error to some logging server or plain log file. This should be done before the call to `Stroke()` since that call will never return.

An example of real life error handling with exception is shown in listing Preparing the data in the introductory example with Sun spots.

### Selecting between text and image based error handling

By default an exception that occurs in the library will create an error image as shown in the previous section. However there might be circumstance where a text based error handling is preferred (usually when graph are created from the command line).

This could be accomplished in two ways. By catching the exception in the script and handle it accordingly or we could slightly modify the default behavior of the default exception handler in the library. How this is done will now be described.

In order to enable a text based error handler we just need to disable the image based error handler. This is done with a call to the method

- `JpGraphError::SetImageFlag($aFlag)`

Since the error handling have global scope this is a static function which can be called as the following example shows

    1
    JpGraphError::SetImageFlag(false); // Enable text based error handling

Adding the line above to a graph script will cause any error to be printed to `STDERR` when the script is called from the command line. This is a very convenient way to show errors when command line constructions like

    $> php mygraph.php > mygraph.png

is used since writing the error to `STDOUT` will cause the error message to be sent back to the console since the call above only redirected `STDOUT` and not `STDERR`.

When the script is called from PHP embedded in a HTTP server (e.g. Apache) there is no concept of a `STDERR` and the error message will just be sent back as normal text to the browser.

### Writing error message to a log file (or system logger)

In addition to the option of having the error sent back as a string to the client it can instead be written to a named log file. The log file name is specified with a call to the (static) method

- `JpGraphError::SetLogFile($aFileName)`

The file needs to be writable by the PHP process. All error messages are appended to the end of the file and each error message is prepended by the date and time (in `RFC 2822` formatted date).

If the filename is given as the string `'syslog'` then the error message will be written to the default system logger instead. When a script is run from, for example, Apache this is normally on Unix '`/var/log/apache2/error_log`'

| Up |
| Home |