24.6. Error handling
Prev | Chapter 24. Linear Barcodes (One Dimensional Barcodes) | Next

## 24.6. Error handling

The barcode module uses the standard library error handling which mean that in case of an error (most likely that the data validation fails) an exception will be raised. Errors can be handled in two ways.

1. By enclosing the script in a `try { ... } catch { ... }` statement

2. By installing a custom default error handler with `set_exception_handler()` when the library throws an error the specified error handler will be called with an instance of the `JpGraphException` class.

The following code snippet shows an example of using a try-catch statment

    1
    2
    3
    4
    5
    6
    7
    8
    9

    <?php
    try {
        $encoder = BarcodeFactory::Create(ENCODING_CODE39);
        $e = BackendFactory::Create(BACKEND_IMAGE,$encoder);
        $e->Stroke('abc123');
    } catch( JpGraphException $e ) {
            echo 'Error: ' . $e->getMessage()."\n";
    }
    ?>

The code when run will give the error

    Error: Data validation failed. Can't encode [abc123] using encoding "CODE 39"

The problem with the input data string is that Code 39 does not support encoding lower case letters. In the case some error handling is still needed but the image error should be displayed it is possible to re-raise the original exception as the following example shows

    1
    2
    3
    4
    5
    6
    7
    8
    9

    <?php
    try {
        $encoder = BarcodeFactory::Create(ENCODING_CODE39);
        $e = BackendFactory::Create(BACKEND_IMAGE,$encoder);
        $e->Stroke('abc123');
    } catch( JpGraphException $e ) {
        JpGraphError::Raise($e->getMessage());
    }
    ?>

The line

    1

    JpGraphError::Raise($e->getMessage());

will display the image error as shown in Figure 24.5

Figure 24.5. Image error - Failed barcode data validation

In the command line barcode utility ( Section 24.7) the alternative method of installing a different default error handler can be seen.

Prev | Up | Next
24.5. Creating barcodes - quick start | Home | 24.7. Generating barcodes on the command line