Saturday, February 6, 2010

Handling errors, warnings and exceptions with one handler.

Introduction

In RawDev, all PHP errors and exceptions can be handled centrally using the Error Reporting library. In addition, RawDev gives more options of error messages than the standard PHP error_reporting level. For example, by default strict errors such as illegal variable references are returned but strict errors such as undefined array offsets are not. RawDev finds that being more strict with variable (and object property) references leads to catching programming mistakes earlier in the development process. Most RawDev users will find this class extremely useful.

Example

In the example below, I trigger several PHP errors: invalid offset, illegal variable reference and illegal object property reference. As you can see, the invalid offset is ignored by default and both other errors are thrown as RExceptions (RawDev Exceptions). Any other RExceptions can be handled by a central handler as well.

<?php

require_once('rawdev/RawDev.php');
require_once(RAWDEV_LIB.'/Core/ErrorReporting.php');

RErrorReporting::singleton()->initialize();

$b = array();
if ($b[0]); # this will not trigger an error

$difficultVariable = 17;
try {
if ($difficultVaariable); # this triggers an error because the wrong variable is used.
}
catch (RException $e) {
print $e->getMessage()."\n";
}

class Test {
}

$a = new Test();

try {
if ($a->b); # this triggers an error because an invalid object variable is used.
}
catch (RException $e) {
print $e->getMessage()."\n";
}

?>

Conclusion

This is just one of these classes that as a developer you will get attached to because it forces you to code a little tighter but avoids having to debug illegal variable and object property mistakes. The central error handling is a nice bonus.

Links

Error Reporting RawDev API Doc

No comments:

Post a Comment