Extending Exceptions
So far, one of the problems with the exception system is all of the exceptions are instances of the same class that only differ by the message they display. This gives us little chance to distinguish between different errors, especially if we localize the error messages into different languages.
It would be beneficial for you to create subclasses of the Exception class that you can then check in code to learn more about the nature of the error:
<?php
class ArgumentTypeException extends Exception
{
function __construct($in_type, $in_expected)
{
parent::__construct("Expected: $in_expected, Received: $in_type");
}
}
class ArgumentRangeException extends Exception
{
function __construct($in_value, $in_bottom, $in_top)
{
$msg = "Value $in_value was not in the range $in_bottom .. $in_top";
parent::__construct($msg);
}
}
?>
Now, you can call the getUserId() function that will give you more information in case of a failure.
<?php
function getUserId($id)
{
if (!is_int($id)) {
throw new ArgumentTypeException(gettype($id), 'int');
}
if ($id < 0 || $id > 6) {
throw new ArgumentRangeException($id, 0, 6);
}
}
getUserId(null);
getUserId(8);
?>
Return Values
Fatal error: Uncaught exception 'ArgumentTypeException' with message 'Expected: int,
Received: NULL' in test.php:22 Stack trace: #0 test.php(30): getUserId(NULL) #1 {
main} thrown in test.php on line 22
Fatal error: Uncaught exception 'ArgumentRangeException' with message
'Value 8 was not in the range 0 .. 6' in test.php:26 Stack trace:
#0 test.php(30): getUserId(8) #1 {main} thrown in test.php on line 26
See also: Extending Exceptions
See also: Custom Exception Handlers
Custom Exception Handlers « PHP::impact([str blog [, str comments]])
April 6, 2007 at 11:08 am