I am working on a PHP rest service. Many errors cause the PHP to terminate without giving any insight into the cause. Surrounding my functions in try catch clauses don't help, the script exits without entering the catch block. Is there a way to catch all/any errors in my PHP scripts?
Check your error_log. Most likely it's a PHP FATAL error that is being thrown before an Exception so it's dead before the catch statement.
To log everything, register a shutdown function in your application together with error_get_last(). For example, this will log all error that will cause your application to unexpectedly die.
function shutdown()
{
$arrError = error_get_last();
if( is_null($arrError) ) {
return true;
}
//Remove the if statement and just have the error_log() if you want to log everything
if( in_array($arrError['type'], array(E_RECOVERABLE_ERROR, E_ERROR, E_USER_ERROR)) ) { //FATAL HANDLER!
error_log("Error caught. ". $arrError['message'] ." in file ". $arrError['file'] .":". $arrError['line']);
//Then maybe do something to make this verbose in your development environment
if( ENVIRONMENT == "dev" ) {
echo "<h3>ERROR</h3> ". $arrError['message'] ." in file ". $arrError['file'] .":". $arrError['line'];
die;
}
}
}
register_shutdown_function('shutdown');
Related
Now that we can catch fatal errors in PHP7 (set_error_handler cannot), would it be a good idea to use it to catch errors on a whole project? Mine is always going through index.php, so I was planning to do this:
try {
//All the code and includes, etc.
} catch(Error $ignored) {
//save the error in log and/or send a notification to admin.
}
I tried first to be sure:
set_error_handler(function(int $number, string $message) {
echo "Error $number: '$message'" . PHP_EOL ;
});
$var = $undeclared_var //The error is sent to the error_handler.
function_dont_exist(); //The error isn't sent to the error_handler.
try {
function_dont_exist();
}
catch(Error $E){
echo "Error"; //That works.
}
Is it a good idea / good practice to envelope the whole code with a try/catch/error to deal with them? It sounds good, but I wonder why I don't see it much. I tried and I believe it works, but it sounds too easy.
Thank you for your help!
I'm using CodeIgniter and am trying to execute code in a try/catch block with the idea that errors will stop execution of the code after the error until the catch block is reached, as you would normally think it would work.
However on encountering PHP Errors, the code is continuing. This is causing a database transaction complete command to execute which is .... very bad if there's an error and all of the instructions weren't carried out properly. For example, I have this code which is executed in an ajax request:
// start transaction
$this->db->trans_start();
try {
$this->M_debug->fblog("firstName=" . $triggerOpts->{'firstXXXName'});
$data = array("test_col" => 123);
$this->db->where("id", 4);
$this->db->update("my_table", $data);
// if got this far, process is ok
$status = "process_ok";
// complete transaction
$this->db->trans_complete();
} catch (Exception $ex) {
// output the error
$this->M_debug->logError($ex);
}
In this code, I'm trying to execute a database update as part of a transaction.
My call to $this->M_debug->fblog() is designed to just log a variable to PHP Console, and I've deliberately tried to log a variable that does not exist.
This causes a PHP error, which I guess is a fatal error, and the desired result is that the code after the log commands fails, and the transaction does not complete. However after this error, despite reporting the PHP error in Chrome console, the code keeps right on executing, the database is updated and the transaction is completed. Would appreciate any help in how i could stop this from happening.
Thanks very much, G
EDIT --
As requested heres fblog(), it's simply a Chrome console log request of a variable
public function fblog( $var ) {
ChromePhp::log( $var );
}
Assuming you're using PHP 7.0 or higher, you can catch PHP errors as well as exceptions, however you need to catch Error or the parent Throwable type rather than Exception.
try {
...
} catch (Throwable $ex) {
//this will catch anything, including Errors and Exceptions
}
or catch them separately if you want to do something different for each of them...
try {
...
} catch (Exception $ex) {
//this will catch Exceptions but not errors.
} catch (Error $ex) {
//this will Errors only
}
Note that if you're still only PHP 5.x, the above won't work; you can't catch PHP errors in older PHP versions.
I've read this thread: php: catch exception and continue execution, is it possible?
Every answer suggests that a try catch will continue executing the script. Here is an example where it doesn't:
try{ $load = #sys_getloadavg(); }
catch (Exception $e){ echo 'Couldn\'t find load average.<br>'; return false; }
I'm running it on xampp on windows, which could be why it errors (it gives a Call to undefined function sys_getloadavg() error when the # is removed), but that isn't the issue in question. It could be any function that doesn't exist, isn't supported or fails - I can not get the script to continue executing.
Another example is if there is a syntax error in the try, say I'm including an external file and parsing it as an array. This also produces an error and stops executing.
Is there any brute force way to continue the script running, regardless of what fails in the try?
Unlike other languages, there's a difference in PHP between exceptions and errors. This would be like a compile error in other languages. that require declaration files. You can't catch or ignore Fatal errors like a function not exisiting. You can test for existence before using though:
if( function_exists('sys_getloadavg') {
try{ $load = #sys_getloadavg(); }
catch (Exception $e){ echo 'Couldn\'t find load average.<br>'; return false; }
}
i call an php pgm per cronjob at different times.
the pgm includes many php-files.
each file sends or gets data from partners.
How can i handle errors in one includes pgm.
at the time, one ftp-connection in an included pgm fails so the complete script crushes.
how can i handle this ?
You should wrap code, which is possible to crash, into try/catch construction. This will throw exeption, but the script will continue to work. More here.
Need to know more about you code inorder to give you definite answer.
In general php errors isn't catchable unless you define your own error handler from which you throw exceptions your self. Using the code below makes most runtime errors catchable (as long as they arent considered fatal)
error_reporing(E_ALL);
set_error_handler(function($errno, $errstr, $errfile, $errline) {
if($errno == E_STRICT || $errno == E_DEPRECATED) {
return true;
}
throw new RuntimeException('Triggered error (code '.$errno.') with message "'.$errstr.'"');
});
Btw, You could also define your own exception handler to display triggered errors with a full stack trace when an exception isn't catched.
Notice! I would not suggest that you add this code to a production website without rigorous testing first, making sure everything still works as expected.
Edit:
I have no idea what your code looks like, but I guess you can do something like:
require 'error-handler.php'; // where you have your error handler (the code seen above)
$files_to_include = array(
'some-file.php',
'some-other-file.php',
...
);
foreach($files_to_include as $file) {
try {
include $file;
}
catch(Exception $e) {
echo "$file failed\nMessage: ".$e->getMessage()."\nTrace:\n".$e->getTraceAsString();
}
}
I am scratching my head trying to debug a PHP transaction that seems to error out one of my consumers. I can detect if my consumer is running by GREPping the process list, before I insert a new message, but no way of knowing what was in there before and what caused the fatal error.
My PHP consumer is roughly:
while($isRunning == true) {
try{
if($frame = $this->stomp->readFrame()) {
$body = $frame->body;
$this->stomp->ack($frame);
}
} catch(StompException $e) {
$msg = 'Stomp Monitor readFrame() Callback Fail: '.$e->getMessage();
error_log($msg);
}
}
Is there any way to catch fatal errors or anything that will break it out of the infinite loop?
Thanks,
Steve
Try setting a top level exception handler
Perhaps there is an exception that your not catching. Catch it and log it so you know why the process dies.