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.
By enclosing the script in a try { ... } catch { ... }
statement
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 | 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 | 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. Image error - Failed barcode data validation
In the command line barcode utility ( Generating barcodes on the command line) the alternative method of installing a different default error handler can be seen.