Error Handler

Error Handler – Flexible error handler plug-in system

Introduction

The HTML_CSS package is implemented with a flexible error handler plug-in system. You may use any error handler that you want. Using PEAR_Error object (default), but also the PEAR_ErrorStack package, or any other error handler you might want to plug in.

Without any configuration, each HTML_CSS API error (basic or exception) will raise a HTML_CSS_Error object that will be return to call script (user script).

Easy to distinct basic PEAR_Error from other PEAR packages to HTML_CSS errors, even if there is a better and more robust solution: HTML_CSS::isError(). But also provide a unique way to retrieve the level of error (warning, error, exception) with the HTML_CSS_Error::getLevel() method.

As usual you can use the PEAR error API as well.

<?php
require_once 'HTML/CSS.php';

$css = new HTML_CSS();

$result $css->setStyle('div''color'5);
if (
PEAR::isError($result)) {
    
// do something when an error is raised
}
?>

and output to screen will give something like :

Exception*: invalid input, parameter #3 "$value" was expecting "string",
instead got "integer"** in html_css->setstyle (file [path_to]\[filename] on line 6)***
     
*

error level

**

message body with context informations

***

call context

Perhaps this standard behavior is not what you want. Don't worry, you can change everything :

  • display or ignore the error
  • display or hide part of message (error level, body, context)

HTML_CSS obey at display_errors and log_errors protocol

Configuring a Handler

A error handler's configuration is determined by the arguments used in its construction. Here's an overview of these parameters.

<?php
require_once 'HTML/CSS.php';

$errorConf = array('error_handler' => 'myErrorHandler',
                   
'push_callback' => 'myError',
                   
// ... more options
                  
);
$css = new HTML_CSS(null$errorConf);
?>

Error Handler configuration parameters
Option Type Description
error_handler callback A valid callback (function) to manage errors raised by the HTML_CSS::raiseError() method. Default is: HTML_CSS::_errorHandler
push_callback callback A valid callback (function) that decides to following action. Default return: PEAR_ERROR_DIE if exception, NULL otherwise.
error_callback callback A valid callback (function) that decides to call a real free user function. Default call: none
message_callback callback A valid callback (function) to control message generation. Default is: HTML_CSS_Error::_msgCallback
context_callback callback A valid callback (function) to control error context generation. Default is: HTML_CSS_Error::getBacktrace
handler mixed any handler-specific settings

Controlling error generation

There are many scenarios in which fine-grained control over error raising is absolutely necessary.

The first level to control error generation is the php.ini directives display_errors and log_errors. When these directives are set to TRUE, then browser and file outputs are effective.

If you want to ignore all errors raised (no display, no logs) and avoid to include PEAR core class, then you should have something like :

<?php
require_once 'HTML/CSS.php';

function 
myErrorHandler()
{
    return 
null;
}

$errorConf = array('error_handler' => 'myErrorHandler');
$css = new HTML_CSS(null$errorConf);
// ...
?>

Note for users of HTML_CSS 1.4.0 or greater

You may want to decide to print (yes/no), log (yes/no) error messages with a full free user function local to HTML_CSS

<?php
require_once 'HTML/CSS.php';

function 
myErrorAction($css_error)
{
    
// do what you want: print and/or log $css_error instance of HTML_CSS_Error object
}

$errorConf = array('error_callback' => 'myErrorAction');
$css = new HTML_CSS(null$errorConf);
// ...
?>

rather than using global PEAR error handler (PEAR::setErrorHandling, PEAR::pushErrorHandling, PEAR::popErrorHandling).

<?php
require_once 'HTML/CSS.php';

function 
myErrorAction($css_error)
{
    
// do what you want: print and/or log $css_error instance of HTML_CSS_Error object
}

PEAR::setErrorHandling(PEAR_ERROR_CALLBACK'myErrorAction');

$css = new HTML_CSS();
// ...
?>

With push_callback option, you can decides to stop script execution (as done with exceptions by default: returns PEAR_ERROR_DIE constant), or continue without filtering (returns NULL).

If you want to write your own callback function for the push_callback option, this one should have two arguments: first one will get the error code, and second will get error level. These are all the necessary informations to do a filtering. Example that follow show how to be aware that a script use wrong argument data type.

<?php
require_once 'HTML/CSS.php';

function 
myErrorFilter($code$level)
{
    if (
$code === HTML_CSS_ERROR_INVALID_INPUT) {
        
error_log('script: '.__FILE__.' used wrong argument data type'1'admin@yoursite.com');
    }
    return 
null;
}

$errorConf = array('push_callback' => 'myErrorFilter');
$css = new HTML_CSS(null$errorConf);
// ...
?>

Error Context Display

In some cases, you may want to customize error generation. For instance, for each error (basic/exception), it is useful to include file, line number, and class/function context information in order to trace it. The default option will be sufficient for most cases but you want perhaps customize the output format (render) of context information.

With this example we will change display and log renders.

<?php
require_once 'HTML/CSS.php';

$displayConfig = array(
    
'lineFormat' => '<b>%1$s</b>: %2$s<br />%3$s',
    
'contextFormat' =>   '<b>File:</b> %1$s <br />'
                       
'<b>Line:</b> %2$s <br />'
                       
'<b>Function:</b> %3$s '
);
$logConfig = array(
    
'lineFormat' => '%1$s %2$s [%3$s] %4$s',
    
'timeFormat' => '%b'
);

$prefs = array(
    
'handler' => array('display' => $displayConfig,
                       
'log'     => $logConfig
));

$css = new HTML_CSS(null$prefs);
// ...
$result $css->setStyle('div''color'5);
?>

Display render will give something like:

Exception****: invalid input, parameter #3 "$value" was expecting "string", instead got "integer"*****
File: [path_to]\[filename] ******
Line: 22 
Function: html_css->setstyle 
     
*

error level

**

message body with context informations

***

call context (file, line, function)

Log render will give something like:

Jun 127.0.0.1******* [exception********] invalid input, parameter #3 "$value" was expecting "string", instead got "integer"*********
     
*

client ip address and execution date

**

error level

***

message body with context informations

To have both display and log output, check the php.ini display_errors and log_errors values : must be set to TRUE.

Let review, step by step, how to get such results.

Remember that with default classes, there are two drivers : display and log that have both their own configuration parameters. You can override these parameters values with the handler entry in the hash of second argument of the HTML_CSS class constructor.

We did it here with the $prefs variable; it's a two key associative array. First key display defines the display driver values, and the second key log defines the log driver values.

Review the display driver custom values. Only two keys:

  • lineFormat
  • contextFormat

are redefined, thats means remains key

  • eol

keep its default value. See table below.

Display driver configuration parameters
Parameter Type Default Description
eol string <br />\n The end-on-line character sequence
lineFormat string <b>%1$s</b>: %2$s %3$s Log line format specification:
  • 1$ = error level
  • 2$ = error message (body)
  • 3$ = error context
contextFormat string in <b>%3$s</b> (file <b>%1$s</b> on line <b>%2$s</b>) Context format (class, file, line) specification:
  • 1$ = script file name
  • 2$ = line in script file
  • 3$ = class/method names

If you don't wish to see context information in the error message, then remove the parameter %3$ in the lineFormat option even if contextFormat is set.

Review now the log driver custom values. Only two keys

  • lineFormat
  • timeFormat

are redefined, thats means six remains keys

  • eol
  • contextFormat
  • ident
  • message_type
  • destination
  • extra_headers

keep their default values. See table below.

Log driver configuration parameters
Parameter Type Default Description
eol string \n The end-on-line character sequence
lineFormat string %1$s %2$s [%3$s] %4$s %5$s Log line format specification:
  • 1$ = time error
  • 2$ = ident (client ip)
  • 3$ = error level
  • 4$ = error message (body)
  • 5$ = error context
contextFormat string in %3$s (file %1$s on line %2$s) Context format (class, file, line) specification:
  • 1$ = script file name
  • 2$ = line in script file
  • 3$ = class/method names
timeFormat string %b %d %H:%M:%S Time stamp format used by strftime
ident string REMOTE_ADDR Client IP
message_type string 3 Destination type used by error_log
destination string html_css_error.log Destination name used by error_log
extra_headers string NULL Extra headers depending of destination type

If you don't wish to see context information in the error message, then remove the parameter %5$ in the lineFormat option even if contextFormat is set.

Custom Error Message Generation

There are two methods of HTML_CSS_Error designed for use with generating error messages efficiently. To use them, you must set the options below in the HTML_CSS class constructor (argument #2):

Option: message_callback

The default message handling callback (HTML_CSS_Error::_getErrorMessage) get an array mapping error codes to error message templates, like so:

<?php
$messages 
= array(
    
HTML_CSS_ERROR_UNKNOWN =>
        
'unknown error',
    
HTML_CSS_ERROR_INVALID_INPUT =>
        
'invalid input, parameter #%paramnum% '
      
'"%var%" was expecting '
      
'"%expected%", instead got "%was%"'
);
?>

Basically, if a variable name is enclosed in percent signs (%), it will be replaced with the value passed in the associative array.

Option: context_callback

The default context handling callback (HTML_CSS_Error::getBackTrace) gets an array of execution functions and discovers where the error was generated.