Bookmark and Share

Tuesday, January 26, 2010

Exception Handling

Examples of exceptions in a web application are model or data layer errors such as "Cannot connect to the database" or user errors such as "Email format incorrect". RawDev offers a simple consistent way of raising these exceptions so that they can (a) be properly logged when necessary and (b) be properly displayed to the end user.

RawDev simply extends the existing PHP Exception with the RException object. Mainly, the added functionality is that you can raise an error with a type (e.g. "division_by_zero"). In addition you can specify a message with parameters (such as used in sprintf). This is (a) handy for the programmer and (b) allows for different languages (i18n) down the road.

Lets get to it:

Example:

require_once('RawDev/RawDev.php');

try {
  throw new RException('email_illegal_format', 'Email [%s] has an illegal format', 'test@test');
}
catch (RException $e) {
  if ($e->type == 'email_illegal_format') print $e->message."\n";
}

?>

In conclusion, RawDev offers a hybrid of using the basic PHP Exception in which you can raise different errors by integer code versus the advanced PHP capability of extending every error type Exception with it's own Exception class (e.g. class EmailIllegalForm extends Exception).

RawDev seeks to (a) avoid using integer codes as error identifies because they are hard to keep track of and (b) creating hundreds of classes for each error type.

Links:
RawDev API Doc

Comments ?

No comments:

Post a Comment