Let's say I have the following piece of code.
To test this, I change the server IP to mimic the error messages. The IP below doesn't exist so the Unhandled Exception message is: Cannot connect to 10.199.1.7. Error 113. No route to host
This displays an ugly screen with PHP code. Is it possible to catch this error?
try {
$ssh = new Net_SSH2('10.199.1.7');
if (!$ssh->login('deploy', $key)) {
throw new Exception("Failed login");
}
} catch (Exception $e) {
???
}
Looked through library.
user_error('Connection closed by server', E_USER_NOTICE);
It triggers errors. You can handle those errors using http://php.net/manual/en/function.set-error-handler.php
e.g.
// Your file.php
$ssh = new Net_SSH2('10.199.1.7');
$ssh->login('deploy', $key);
// bootstrap.php
// This will catch all user notice errors!!!
set_error_handler ('errorHandler', E_USER_NOTICE)
function errorHandler($errno, $errstr, $errfile, $errline) {
echo 'Error';
// Whatever you want to do.
}
You can use # in front of you function call. # operator
Related
if i have the code below:
try {
//call function a
$object->function_a();
//call function b
$object->function_b();
//call function c
$object->function_c();
}
catch(Exception $e) {
$error->track_error();
}
how can i catch syntax errors, like someone is changing the function_b() name to function_d() which doesn't exists.
it seems that try and catch doesn't catch syntax errors, it doesn't work without an if statement to check if something is wrong.
but if i can expect an error with an if statement, why do i need try and catch, i can just write something like this:
if(//something is false) {
$error->track_error();
}
what i'm looking is something that will create an exception and jump to a catch block on the whole try scope, when any php error (including syntax) is happening, catch it and then get the details with error_get_last() or similar function for error logging inside the db.
is this possible?
You can use set_error_handler() to throw a custom Exception :
set_error_handler(function(int $errno, string $errstr, string $errfile = '', int $errline = 0) {
throw new Exception("$errstr ($errfile, line $errline)");
});
I'm writing code that randomly generates expressions for a genetic algorithm for code optimisation purposes. The generated expressions are eval'ed for fitness. Some expressions will generate errors and I need to be able to catch these and act appropriately.
I have the following code (simplified from the original):
set_error_handler(function($errno, $errstr, $errfile, $errline, $errcontext) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
$expression = '$y=~!7;';
try {
eval($expression);
} catch (Exception $e){
echo 'Expression failed';
} catch (ParseError $e){
echo 'Expression failed';
}
This throws the following error:
PHP Fatal error: Unsupported operand types in ..... : eval()'d code on line ....
But this error is not caught in either catch block.
I've set my own error handler so that all errors are promoted to exceptions.
How do I catch this error?
Note: I am very aware that using eval is dangerous, but there is strictly no user input in my code.
At least in PHP 7.1+, eval() terminates the script if the evaluated code generate a fatal error. For example:
#eval('$content = (100 - );');
(Even if it is in the man, I'm note sure it acted like this in 5.6, but whatever)
To catch it, I had to do:
try {
eval('$content = (100 - );');
} catch (ParseError $e) {
$content = null;
}
This is the only way I found to catch the error and hide the fact there was one.
I am reading some extra information from Redis and the desired behaviour is to skip connection error silently, if any:
try {
$r = new Redis();
$r->connect("127.0.0.1", "6379");
} catch (Error $e) {
;
} catch (Throwable $e) {
;
}
If Redis fails, monitoring system will show alert to right people to fix it.
Unfortunatelly the code above still causes Yii to fail and produce HTTP 500:
2018/04/09 12:28:04 [error] [php] Redis::connect(): connect() failed: Connection refused
What am I doing wrong?
You need to catch the Exception thrown...
try {
$r = new Redis();
$r->connect("127.0.0.1", "6379");
} catch (\Exception $e) {
;
}
I think you can catch the very specific exception of Predis\Connection\ConnectionException if you need to.
I'm trying to ignore a PHP error via a try catch block but it doesn't seem to be working? I'm using it inside of of my controllers in Laravel.
try {
if (!self::isEmulatorOnline()) {
return;
}
$MUSdata = $command . chr(1) . $data;
$socket = \socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
$connect_timeval = array(
"sec"=>0,
"usec" => 100
);
\socket_set_option(
$socket,
SOL_SOCKET,
SO_SNDTIMEO,
$connect_timeval
);
\socket_connect($socket, Config::get('frontend.client_host_ip'), Config::get('frontend.mus_host_port'));
\socket_send($socket, $MUSdata, strlen($MUSdata), MSG_DONTROUTE);
\socket_close($socket);
}
catch(\PHPException $exception) {}
As you can see I am trying to silent the error exception, I know it is advised not to but its via an ajax request where I handle if the client IP and port can't be accessed using a different method.
Does anyone know why its returning the error exception even when making it silent out using try catch?
The error I am getting is
1/1) ErrorException
socket_connect(): unable to connect [10061]: No connection could be made because the target machine actively refused it.
On this line:
\socket_connect($socket, Config::get('frontend.client_host_ip'), Config::get('frontend.mus_host_port'));
You're trying to catch the wrong exception. socket_connect() throws an ErrorException and not an PHPException. You can also specify just the Exception class to catch all unhandled exceptions.
You can also add multiple catch blocks if you want to catch multiple exception classes to handle them differently.
Example:
try {
//
} catch (ErrorException $ex) {
// here you go.
}
In laravel you can catch error like this.
Try logging this
try {
//
} catch (\Exception $e) {
// catch error message
Log::info($e->getMessage());
// get http error code
Log::info($e->getCode());
}
I want to create a simple PHP status file at the root of a Drupal website. This file will be called by a monitoring system such as Nagios. I want to fully customize the output and add some additional details into the error message (as a plain text string).
I've tried the following code:
define('DRUPAL_ROOT', __DIR__);
require_once realpath(DRUPAL_ROOT . '/includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
restore_exception_handler();
restore_error_handler();
function exception_handler($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
echo "PHP Error: [$errno] $errstr<br />\n";
return true;
}
$old_error_handler = set_error_handler("myErrorHandler");
try {
db_query('SELECT COUNT(nid) FROM {node}');
echo 'ok';
}
catch (\PDOException $e) {
echo "Database problem";
}
catch (Exception $e) {
echo "Unexecpted error: " . $e->getMessage();
}
However, when I try to disable the database (by stopping the service), a Drupal custom error appears in HTML format.
You must go to admin/config/development/logging and check the option None to hide errors