I wonder how much effort I have to make to format useful debugging information when creating exception messages, or should I just trust the user to provide the correct information or defer collection of information to the exception handler?
I see many people who make their exceptions, for example:
throw new RuntimeException('MyObject is not an array')
or default exception extensions with custom exceptions that do nothing but change the name of the exception:
throw new WrongTypeException('MyObject is not an array')
But this does not provide much debugging information ... and does not force the formatting with the error message. Thus, you can get exactly the same error producing two different error messages ... for example, "Could not connect to database" vs "Could not connect to db"
Of course, if it bubbles up, it will print a stack trace, which is useful, but this does not always tell me everything I need to know, and usually I have to start firing from var_dump () to find out what went wrong and where. .. although this may be somewhat offset by a decent exception handler.
I'm starting to think of something like the code below, where I need an exception thrower to provide the necessary arguments to create the correct error message. I think this may be the way to do this:
- A minimum level of useful information should be provided.
- Produces several consistent error messages
- Templates for exception messages in one place (exception classes), so itβs easier to update messages ...
But I see a drawback in that they are harder to use (you need to look for a definition of an exception) and, thus, can prevent other programmers from using the provided exceptions ...
I would like to comment on this idea and best practices for a consistent flexible structure for exception messages.
class MyWrongTypeException extends RuntimeException { public function __construct($objectName, $object, $expected, $message = '', $code = 0) { $receivedType = gettype($object) $message = "Wrong Type: $objectName. Expected $expected, received $receivedType"; debug_dump($message, $object); return parent::__construct($message, $code); } }
....
function debug_dump(&$message, &$object) { if (App::get_mode() == 'debug') { ob_start(); var_dump($object); $message = $message . "Debug Info: " . ob_get_clean(); } }
Then used as:
// Hypothetical, supposed to return an array of user objects $users = get_users(); // but instead returns the string 'bad' // Ideally the $users model object would provide a validate() but for the sake // of the example if (is_array($users)) { throw new MyWrongTypeException('$users', $users, 'array') // returns //"Wrong Type: $users. Expected array, received string }
and we can do something like nl2br in a special exception handler to do something nice for html output.
Read: http://msdn.microsoft.com/en-us/library/cc511859.aspx#
And nothing like that is mentioned, so maybe this is a bad idea ...