I have a script with an exception handler. This exception handler cleans up a couple connections, prior to the script exiting after an exception.
I would like to re-throw the exception from this exception handler so that it is handled by PHP's own last-resort exception handler, where the error is written to PHP's error log, or whatever the default is, as configured in PHP.ini.
Unfortunately, this doesn't seem like a possibility, as outlined here:
http://www.php.net/manual/en/function.set-exception-handler.php#68712
Will cause a Fatal error: Exception thrown without a stack frame
Is there another way to bubble the error up the stack so that PHP handles it after my exception handler is done cleaning up?
You can not re-throw from the exception handler, however, there are other places you can. For example you can de-couple the re-throw from the handler by encapsulating things into a class of it's own and then use the __destruct() function (PHP 5.3, Demo):
<?php
class ExceptionHandler
{
private $rethrow;
public function __construct()
{
set_exception_handler(array($this, 'handler'));
}
public function handler($exception)
{
echo "cleaning up.\n";
$this->rethrow = $exception;
}
public function __destruct()
{
if ($this->rethrow) throw $this->rethrow;
}
}
$handler = new ExceptionHandler;
throw new Exception();
Put this into my error log:
[29-Oct-2011 xx:32:25] PHP Fatal error: Uncaught exception 'Exception' in /.../test-exception.php:23
Stack trace:
#0 {main}
thrown in /.../test-exception.php on line 23
Just catch the exception and log the message yourself, then rethrow.
try {
$foo->doSomethingToCauseException();
} catch (Exception $e) {
error_log($e->getMessage());
throw $e;
}
If you bubble up to the top and PHP is unable to handle, it will result in uncaught exception.
Will cause a Fatal error: Exception thrown without a stack frame
This error means that your exception is thrown from a code that is not part of the script (as far as PHP knows). Examples of such code include custom exception handler set with set_exception_handler() and any class destructor method. There's no choice but to NOT throw an exception from such a code.
If you want PHP native error handling, I'd suggest you to call trigger_error() instead. It should log the error if you don't have custom error handler and you use suitable error type. For example, E_USER_ERROR should be fine.
Just rethrow the exception as a RunTimeException and it will keep the stacktrace :)
try {
// bad exception throwing code
} catch (Exception $e) {
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}
From http://www.php.net/manual/en/function.set-exception-handler.php#88082
i read:
Another solution is to restore the error handler at the beginning of the exception handler.
Have you tried it?
Related
I am stumbling a bit with finding a way to test that my exception handler is being called upon thrown Exception.
This is the idea that I initially working with for the testing:
class ClientSpec extends ObjectBehavior
{
function it_should_catch_exceptions(Config $config)
{
$e = new Exception('test exception');
$this->catchException($e)->shouldBeCalled();
throw $e;
}
}
The Client has a method catchException which will be set as exception handler through set_exception_handler: http://php.net/set_exception_handler.
Running this test gives me this feedback: no beCalled([array:0]) matcher found for null, so I've also tried to do create a spec for Exception and do the following:
class ExceptionSpec extends ObjectBehavior
{
function it_should_trigger_opbeat_client_when_thrown(Client $client)
{
$client->catchException($this)->shouldBeCalled();
throw $this->getWrappedObject();
}
}
But running this test returns another error: exception [exc:Exception("")] has been thrown
How can I test that my exception handler is called?
I'm afraid you cannot test an exception handler using phpspec, PHPUnit or other similar testing tool because they wrap the test you write into a try-catch block in order to catch any uncaught exception and report it.
On the other hand, the documentation of set_expection_handler() says:
Sets the default exception handler if an exception is not caught within a try/catch block.
Since phpspec catches all the exceptions your test code throws, the exception handler you install does not have a chance to run :-(
I think all uncaught exceptions end their adventure in ExampleRunner.php at line 96
I've written error handling class which divided all errors into the normal ones (notices, warnings, ...), and the critical ones.
Now I've found out that it's a good practice to convert all errors into exceptions. It would also shorten my code.
However, I'm not sure how to handle this...
Are there exceptions that don't stop scripts execution, and exceptions that do? If there aren't...how to differ converted errors?
Converting errors into exception is done by calling set_error_handler() and throw new ErrorException() in there...What's next? set_exception_handler() is called automagically?
Caught exceptions do not stop your script, all uncaught ones do.
No, set_exception_handler() is not called automatically, you can do that if you like.
The exception handler you set with set_exception_handler() gets called after an exception has gone uncaught, it is the last piece of code that gets called before the script terminates. Make sure it doesn't cause an error/exception, or it will end badly.
Are there exceptions that don't stop scripts execution, and exceptions that do? If there aren't...how to differ converted errors?
Exceptions don't stop script execution if they're caught. To recognize a converted error:
try {
// ...
} catch (ErrorException $e) {
// converted error (probably)
} catch (Exception $e) {
// another kind of exception; this basically catches all
}
Or:
function handle_exception(Exception $e)
{
if ($e instanceof ErrorException) {
// converted error (probably)
} else {
// another kind of exception
}
}
set_exception_handler('handle_exception');
Note that ErrorException can be thrown by any piece of code, but it was meant to convert regular errors in set_error_handler() registered functions only.
Converting errors into exception is done by calling set_error_handler() and throw new ErrorException() in there...What's next? set_exception_handler() is called automagically?
If the thrown ErrorException from your error handler function is not caught anywhere else in your code, the registered exception handler (set using set_exception_handler()) will be called.
Any uncaught exception will stop execution of your script.
When an exception is thrown, code following the statement will not be
executed, and PHP will attempt to find the first matching catch block.
If an exception is not caught, a PHP Fatal Error will be issued with
an "Uncaught Exception ..." message, unless a handler has been defined
with set_exception_handler().
See docs about this
As for set_exception_handler() - it is not called automatically, but it is your last resort to react to the problem that occured
Sets the default exception handler if an exception is not caught
within a try/catch block. Execution will stop after the
exception_handler is called.
Keep in mind that you can only convert Warnings into Exceptions, errors cannot be converted to Exceptions because the error handler doesn't run.
set_error_handler(function ($severity, $message, $file, $line) {
echo 'You will never see this.'
});
// Provoke an error
function_that_does_not_exist();
It is possible to "catch" them using a shutdown function, but that is out of the scope of the question.
My app has a registered shutdown function and it seems there's some issues with that and my method of using an exception with a try/catch to exit the application (instead of using the exit() method due to FastCGI not liking this).
My problem is that if another exception is thrown in the try/catch block that isn't the ExitApp exception, it causes some unexpected results and the end result is the ExitApp exception isn't caught.
I'm seeing this on PHP 5.3.6, going to test it on another version now, but I'm curious if anyone can immediately point out what's wrong here.
<?php
// Define dummy exception class
class ExitApp extends Exception {}
try {
// Define shutdown function
function shutdown() {
echo "Shutting down...";
throw new ExitApp;
}
register_shutdown_function("shutdown");
// Throw exception!
throw new Exception("EXCEPTION!");
} catch(ExitApp $e) {
echo "Catching the exit exception!";
}
/**
* Expected Result: Uncaught Exception Error and then "Catching the exit exception!" is printed.
* Actual Result: Uncaught Exception Error for "Exception" and then Uncaught Exception Error for "ExitApp" even though it's being caught.
*/
You have wrong expectations from your code. Firstly, if you throw exception in your shutdown function, you will always end up with uncaught exception - shutdown functions are called outside tr/catch block.
Secondly you have no attempt to intercept unknown exception - you are only catching ExitApp types. you may want to try something like this:
try {
//some stuff
} catch(ExitApp $ea) {
//normal exit, nothing to do here
} catch(Exception $e){
//something rather unexpected, log it
}
Your shutdown() function is not even in a try/catch block, so it will never jump down to the catch for this exception type. It is going to run on exit so you will not longer be in that try/catch block.
On a more spiritual, try/catch is not meant for flow control. I'm not quite sure why you're trying to throw this to cause script exit, rather than just calling your own shutdown() method.
Hope that helps.
For some reason, exceptions thrown in an __autoload function aren't being caught when trying to call a static method on a class that doesn't exist yet (PHP 5.3.9).
See this sample code:
<?php
function __autoload($class)
{
throw new Exception('loaded ' . $class . "\n");
}
try {
echo "Object: ";
$test = new Log();
}
catch (Exception $e)
{
error_log($e->getMessage());
}
// Exception is caught with static var.
try {
echo "Static var: ";
Log::$blah;
}
catch (Exception $e)
{
error_log($e->getMessage());
}
// Fatal error occures with static method.
try {
echo "Static method: ";
Log::blah();
}
catch (Exception $e)
{
error_log($e->getMessage());
}
The exception is caught on the first 2 cases (new object and a static property of an unknown class), but is not caught on calling the static method.
PHP mixes errors and exceptions. In this case, the fatal error is "thrown" before the exception could be caught. It's about priorities. Calling an undefined function and giving the fatal error has a higher priority here than handling the exception, the code already stopped (Demo). Fatal errors itself can not be catched.
As you can not catch fatal errors with a try/catch block, your script stops at the fatal error.
Same would be for an undefined static property of a defined class. It would trigger a fatal error as well you won't be able to catch.
You can however turn errors into exceptions and catch those, however this does not work with fatal errors (Demo). I assume this is the root limitation you're running into: Fatal error brings script execution down, regardless if it appears inside a try/catch block or not. Exception handling is brought down as well.
Additionally, PHP 5.5.0-dev and PHP 5.4.0beta2-dev crashes with a simliar to yours code example. Which makes me believe that in the upcoming PHP version there will be a bug which could be considered a flaw. It might be worth to report this against PHP 5.4.
See also Exception slipping exception handler which illustrates your problem without the overhead of __autoload.
Yes, PHP have a problems with exceptions thrown in an __autoload.
But you can use one interesting trick:
function __autoload($class)
{
eval("class $class {
static function __callStatic(\$name,\$val){
throw new Exception('Loaded ' . $class . PHP_EOL);
}
}");
throw new Exception('Loaded ' . $class . PHP_EOL);
}
And don't forgot to implement work with namespaces in evaled expression.
I have some code in a __destruct() method that sometimes throws an exception. The __destruct() method is being called during another exception and I'm seeing a vague error:
PHP Fatal error: Ignoring exception from exampleClass::__destruct() while an exception is already active
which is hiding the actual exception that's being called. I'd like to do something like:
public function __destruct()
{
try
{
// do work here
}
catch(Exception $e)
{
// check if we're already in an exception and log it
if(already_in_exception())
{
error_log($e->getMessage());
}
// normal destruct, re-throw
else
{
throw $e;
}
}
}
Bonus points if it's PHP 5.1.6 compatible!
Thank you in advanced!
Your problem isn't because you're throwing an exception from within another, it's because you're throwing an exception from a destructor.
From php.net: http://php.net/manual/en/language.oop5.decon.php I quote:
"NOTE: Attempting to throw an exception from a destructor (called in the time of script termination) causes a fatal error."
Rethink your logic abit and do this prior to deconstruction.