PHP 5.3 Exception sanity check - does PHP really print inner exception message?
I think this is a little weird.
I'm running a script, which runs a program. I store the latest output in a variable. If the program or my script for different reasons cause an exception in the script, I catch t开发者_如何学Pythonhe exception, append the error log, and rethrow it. A few levels above I catch it again, log the total message, and rethrow it to shut down the script.
When PHP command line dies though, it seems to print only the inner exception message in the stack trace, because there is no mention of my message. It even says Uncaught "Exception" which is the inner exception I throw when testing, while the outer exception is a custom type. getMessage() returns the complete message as expected.
PHP Fatal error: Uncaught exception 'Exception' with message 'This is a test error message.' in /home/x/Documents/project/file.php:14
Stack trace:
Am I insane, is this expected behaviour? Should I go to sleep?
UPDATE:
At the "root" level I have this:
catch(Exception $e)
{
$access->logError($e->getMessage());
print 'Actual error: ' . $e->getMessage() . "\n";
print get_class($e);
throw $e;
}
the print-statement prints the real message I am expecting, the aggregate. throw $e yields the inner exception message... print get_class($e)
prints CustomException...
This is the declaration of CustomException:
class CustomException extends Exception
{
function __construct($message, $prev)
{
parent::__construct($message, -1, $prev);
}
}
This is how it is used:
catch(Exception $e)
{
$message = $e->getMessage() . $logString;
$resultReporter->reportError($message);
$e = new CommandException($message, $e);
$throw e;
}
Turns out after all that, I guess it's expected behaviour.
What PHP appears to do is work backwards up the exception stack when it has the chance to display it.
See the following output:
Rudis-Mac-Pro:~ rudi$ php ex.php
PHP Fatal error: Uncaught exception 'Exception' with message 'I'm an inner exception' in /Users/rudi/ex.php:3
Stack trace:
#0 {main}
Next exception 'Exception' with message 'I'm the outer exception' in /Users/rudi/ex.php:6
Stack trace:
#0 {main}
Next exception 'Exception' with message 'I'm the reeally outer exception' in /Users/rudi/ex.php:8
Stack trace:
#0 {main}
thrown in /Users/rudi/ex.php on line 8
This was produced from the fairly basic code:
<?php
try {
throw new Exception("I'm an inner exception");
} catch(Exception $ex) {
try {
throw new Exception("I'm the outer exception", -1, $ex);
} catch(Exception $iex) {
throw new Exception("I'm the reeally outer exception", -1, $iex);
}
}
It probably does this so that the developer can get a better view of what's actually happening, rather than an abstracted one. Makes a bit of sense if you think about it ^_^
Now go to bed ;-)
精彩评论