An exception is thrown in my shutdown function and not caught within a try/catch block, for example:
<?php
set_exception_handler(function($e){
echo "exception handled"; // not echoed
});
register_shutdown_function(function(){
throw new Exception("test"); // this should be caught by the exception handler above, but it doesn't
});
Live run.
Running the above code gives:
Fatal error: Uncaught exception 'Exception' with message 'test'
However PHP Manual claims:
set_exception_handler 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.
Why does exception_handler not catch the exception thrown?
Because it is beyond the scope...
http://www.php.net/manual/en/function.register-shutdown-function.php
Registers a callback to be executed after script execution finishes or exit() is called.
It must be stripping down your handlers as the execution of your script has finished and is in fact shutting down.
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.
Consider the following two PHP (5.4) scripts. Why is the callback passed to register_shutdown_function only invoked when script A is executed, but not when script B is executed?
Script A
set_error_handler(function() {
throw new Exception();
});
register_shutdown_function(function() {
echo "shutdown handler invoked\n";
});
undefined();
// "shutdown handler invoked" IS displayed
Script B
set_error_handler(function() {
throw new Exception();
});
register_shutdown_function(function() {
echo "shutdown handler invoked\n";
});
$undefined->undefined();
// "shutdown handler invoked" IS NOT displayed
It's a bug—if the callable registered with set_error_handler throws an exception, the shutdown function will not be invoked.
In this particular case, the following chain of events happens:
Non-fatal error is triggered (Undefined variable: undefined)
User error handler is invoked
Exception is thrown
Fatal error is triggered (Call to a member function undefined() on a non-object)
Shutdown function is not invoked, due to existing exception
The existing bug reports at https://bugs.php.net/61767 (with patch!) and https://bugs.php.net/60909 have additional details.
Here is what I found out.
register_shutdown_function is called upon exit.
$undefined->undefined(); triggers E_NOTICE error because $undefined is undefined as a variable which goes through set_error_handler. if you call throw new Exception, php for some reason doesn't trigger register_shutdown_function handler when exiting just crashes, if you want to throw an exception maybe you can call your exception function directly.
If you make a dummy class and define $undefined, but doesn't make a member function called undefined, it will be behave in the same way as calling undefined() as below
undefined(); triggers E_ERROR which immediately exits triggering shutdown_function handler
You could do this in the shutdown function beside using error handler to catch different types of errors:
function shutdown_function_handler(){
if ($error = error_get_last()){
switch ($error['type']){
case E_ERROR:
case E_USER_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
echo " ERRROR:".$error['message'];
}
}
}
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.
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?