I am running a cronjob script which completely freezes within a try / catch statement (which is inside a while loop).
The catch phrase is working as it's logging the error (which i put there) but then it freezes completely without any output.
after that i only put echo "error"; inside the catch pharse but it does not output and freezes again.
when adding die; it prompts and the script stops as expected - but i want to catch the error and continue the script.
while($rs = $res->fetch_assoc())
{
try
{
$rc = new c_movie();
$result = $rc->search();
} catch(Throwable $t)
{
echo "ERROR!!!!"; // freezing here, does not echo
}
}
any idea what could be causing the script to freeze?
thanks
I finally found out by myself .. my code was using get_headers() which caused the freeze when trying to load a URL which had 404. Seems like the server is somekind of caching it and freezes and won't trigger the exception. Very Strange ..
I'm using WAMP as my platform. Running the following code (pdodb is a framework for working with PDO):
<?PHP
$mysql = pdodb::getInstance();
$query = " SELECT PhysicalID FROM PhysicalInfo
WHERE barcode=0";
$mysql->Prepare($query);
$res = $mysql->Execute($query);
?>
PHP halts upon "Execute()" e.g. the next lines are not executed! I used try/catch to catch (Exception e) but even the error message in catch is not displayed! needless to say that there's no use inserting $res->errorInfo() after the execute() because it won't run either. Although, if I set the database in my code:
$query = " SELECT PhysicalID FROM **carinfo.**PhysicalInfo
WHERE barcode=0";
The code runs perfectly. Using PHPMyAdmin, I get the following error on the first query:
#1046 - No database selected
The problem is:
Why does PHP halt on this and the rest of the program after
$mysql->Execute($query); is not run.
How could I get the error message to check for it in my program (it's pretty ugly to have your code stop without any warning).
I've never worked with advanced error handling, and I can't find an obvious answer searching.
In the scope a script (require_once) how do you set up a custom "die" message?
Generally my users see the page-load die with no response. I'd like to direct them to a help file regarding memory so they absolutely cannot miss the solution.
You can kill a script and output a message using the die() command
die("Your message here");
You can also throw custom exceptions in PHP 5+, and catch them and at that point output a message to the users.
http://php.net/manual/en/language.exceptions.php
require_once automatically stops execution if it fails.
Try e.g. (include_once file.php) or header('Location: http://.../path/to/help');, or
if(!(include_once file.php)) {
// redirect?
}
I have a script that produces a report. For most widgets* it produces a report with no problem. For a particular widget it exits in the middle during a mysql query and a 500 is returned to the browser. By inserting writes to the php_error log I know the exact last line to be executed and it's always the same line. It's not a timeout because other widget reports run longer (and it bombs out in about 10 seconds).
Also, I've tried running the query it's trying to run in phpadmin and it runs OK.
When this abort occurs I see nothing appear in php_error.log, nothing in apache's error log and when I surround the offending statement with a try/catch, no exception is caught.
Is there somewhere else I can look that might show what error is occurring?
* by widget I'm not referring to a UI component. I'm using widget in the sense of fictional product from a fictional company
addendum ======================================================================
Since it was requested I posted the code although I think the problem isn't the code since it works in all but this once case. The problem is more likely in the data for this particular case.
error_log('['.__FILE__.']['.__LINE__."] check");
$table = new metrics_sessions();
//here I print out the SQL statement that will eventually be executed
error_log('['.__FILE__.']['.__LINE__."] check: "."guider_slug=? ".($effective_mindate!=null?" and date>'".$effective_mindate."'":"").($effective_maxdate!=null?" and date<'".$effective_maxdate." 23:59:59'":"").($effective_version!=0 && $effective_version!="all"?" and version=".$specific_version:"").($effective_campaign!==null && $effective_campaign!="all" ?" and campaign='".$effective_campaign."'":"")." order by date");
// BELOW IS THE LAST LINE I SEE IN PHP ERROR
error_log('['.__FILE__.']['.__LINE__."] check");
try {
$sessions = $table->Find("guider_slug=? ".($effective_mindate!=null?" and date>'".$effective_mindate."'":"").($effective_maxdate!=null?" and date<'".$effective_maxdate." 23:59:59'":"").($effective_version!=0 && $effective_version!="all"?" and version=".$specific_version:"").($effective_campaign!==null && $effective_campaign!="all" ?" and campaign='".$effective_campaign."'":"")." order by date",array($param_gslug));
error_log('['.__FILE__.']['.__LINE__."] check");
}catch(Exception $e){
error_log('['.__FILE__.']['.__LINE__."] check");
error_log('Caught exception: '.$e->getMessage());
error_log('File: '.$e->getFile());
error_log('Line: '.$e->getLine());
error_log('Trace: '.$e->getTraceAsString());
}
error_log('['.__FILE__.']['.__LINE__."] session count: ".count($sessions));
Check for error supression operators (#) in your code and the code you are calling.
Try editing your error php.ini file to allow warnings and error codes to be displayed.
error_reporting = E_ALL | E_STRICT
This would be sufficient.
I would like to be able to discard a partially rendered page and show an error page in PHP.
I already know about set_error_handler(), but it can only trap certain types of errors. I would like to know how to show an error page when an error type which can't be trapped by set_error_handler() is raised.
Unfortunately, it seems that the following code, when run with PHP 5.3.2 on Apache 2.2, doesn't do what I would expect it to do:
<?php
// Start the output buffer
ob_start();
// Output something into the buffer.
// I only want this to be displayed if I call one of the
// ob_flush functions or echo the buffer myself later.
echo "yep";
// Call a function I know not to exist in order to raise
// an error which cannot be trapped by set_error_handler()
// and would, if display_errors was On, output "Fatal
// error: Call to undefined function fwee()..."
function_which_does_not_exist();
// This will never be executed.
$out = ob_get_clean();
The output of the script is:
yep
Whereas I would expect it to output nothing (or spew error info and only error info if display_errors() is on).
I have confirmed using LiveHTTPHeaders that PHP 5.3.2 does send a 500 error to the browser when display_errors is off (and a 200 when it's on) using the version of apache supplied by MacPorts, but it only ever spits 200s when using PHP 5.3.1 on XAMPP.
I tried setting ErrorDocument 500 "test" in the apache configuration (confirmed to be working by doing the same for 404) but PHP never shows the custom error, even when the entire contents of the script is just header('HTTP/1.1 500 Internal Server Error');
I'm not sure what else to do to make sure a partially rendered page is replaced with a simple error.
I can also confirm that this happens in the Yii framework. If I edit the view for the "about" page in the blog demo to have a line which reads <?php echo function_which_does_not_exist() ?>, I get a partially rendered page.
You could pass ob_start the name of a callback function, that is executed before the output is flushed on ob_get_clean().
This callback function seams to be executed even if an error occured on the page.
This way you could do something like this:
<?php
$endReached = 0;
function outpu_cb($buffer) {
global $endReached;
if ($endReached) return $buffer;
else return 'Your error message';
}
// Start the output buffer
ob_start('outpu_cb');
// Output something into the buffer.
// I only want this to be displayed if I call one of the
// ob_flush functions or echo the buffer myself later.
echo "yep";
// Call a function I know not to exist in order to raise
// an error which cannot be trapped by set_error_handler()
// and would, if display_errors was On, output "Fatal
// error: Call to undefined function fwee()..."
function_which_does_not_exist();
// This will never be executed.
$endReached = 1;
echo ob_get_clean();
?>
I think the only right way to do this is by using correct output buffering, than you don't have to rely on specific webserver or browser behaviour.
Best you'd use a MVC framework to handle this for you. All output is buffered until all systems are go, so when an error occurs you can take another route, clear the current buffer and display some nice error message.
You can also use the ob_*() family of functions.
You have to call ob_start() as the very first thing in your script (well, before any output is generated)
Install an error_handler to fetch errors
When an error occured, clean the buffer and re-route your app logic to display some nice userfriendly error message
If your talking about E_FATAL or other such errors yes you can catch them with a custom error handler using set_error_handler().
All you need to add is a shutdown function.
// Set the error handler
set_error_handler(array('error', 'handler'));
// Catch E_FATAL errors too!
register_shutdown_function(array('error', 'catch_fatal'));
// Set the exception handler
set_exception_handler(array('error', 'exception'));
// Manually return a new exception
function catch_fatal()
{
if($e=error_get_last())Error::exception(new ErrorException($e['message'],$e['type'],0,$e['file'],$e['line']));
}
Take a look at http://micromvc.com or http://kohanaphp.com/ to see how it's done.
An old question, but for the record I'd suggest avoiding this issue rather than handling it.
My own approach is to build the response in a response object rather than echoing it as you go along, and only echo the output once the full response has been processed without error. This requires a template system that parses your template and builds your response into a string, in contrast to a classic PHP template which echoes output from your placeholders.
This way you entirely avoid PHP's crufty management of the output cache in error states.