I am using this script here and it does not always want to connect to the server I set it to. When it doesn't, it'll show an error "Failed to receive status". I'm wondering how can I test to see if this happens and put it into an if statement?
For example:
if (isError) return false;
Here is the part which checks for the error or not in the script:
if( !$Data )
{
throw new MinecraftQueryException( "Failed to receive status." );
}
Just use try ... catch block. But make sure you are logging the exception message. It'll be helpful for future investigation.
try
{
$Query = new MinecraftQuery( );
// .. do mine craft connection
$Query->Connect( '...', 25565 );
print_r( $Query->GetInfo( ) );
} catch(MinecraftQueryException $mqe){
// log $mq->getMessage() for future investigation
return false;
}
You'll want to surround the Connect call inside a try/catch block in order to catch the exception, and then put the failure code inside the catch block. You can read more about exceptions in the PHP manual:
try {
$query->Connect();
} catch(MinecraftQueryException $exception) {
return false;
}
Related
I know this is a weird on, but in my code, i have development mode errors, and production mode errors. This is the function i have:
private function error($message, $mysql_error = null){
if( DEVELOPMENT_MODE ){
$exp = new Exception();
$trace = $exp -> getTrace();
array_shift( $trace ); // removes this functions from trace
$data["Error Mg"] = $message;
$data["MySQL Er"] = ( is_null ( $mysql_error ) ) ? "" : $mysql_error;
array_unshift($trace, $data );
fkill( $trace ); // formats array and then dies
}
else{
throw new Exception ( $data );
}
}
I wrote this function in my database class, so that if an error happens, I don't have to provide the check if we're in development mode or not!
So I thought I could externalise the re-usable code. However, because I'm throwing an exception from this function, I'm basically just using a function, that will return a thrown error. Pretty useless in production mode.
I would have to do this every time i want to use it:
try{
$this -> error( "Invalid Link After Connect.", mysql_error () );
} catch ( Exception $exp ){
throw $exp;
}
RATHER THAN JUST
$this -> error( "Invalid Link After Connect.", mysql_error () );
so to avoid writing a try ... catch block for every error function I want to call... is there any way to throw the exception 2 levels up?
An exception will automatically travel up the call chain until it reaches the highest level. If it's not caught there, program execution terminates due to an uncaught exception. The whole point of exceptions is to be able to have errors bubble up. You don't need to throw harder or do anything special to "throw it up 2 levels", that's what it does by definition.
Just omit the try/catch block. Exceptions automatically propagate up as far as they can until something catches them; you don't need to explicitly re-throw them at every level of the call stack.
This...
try{
$this -> error( "Invalid Link After Connect.", mysql_error () );
} catch ( Exception $exp ){
throw $exp;
}
is exactly equivalent to this:
$this -> error( "Invalid Link After Connect.", mysql_error () );
Use Multiple catch Blocks
use admin table which has field
Mode Value
0 Production
1 Debug
the first catch which matches the exception is executed
Example
try {
if (!$bDBConnection && $row['mode'] ==0 ) {
throw new Produciton_DBException("Problem with Database");
}
else
{
throw new Debug_DBException("Problem with Database");
}
}
catch(Produciton_DBException $e)
{
// display suitable error messages
}
catch(Debug_DBException $ex)
{
// Exception falls through until a match is found
}
I'm querying a whole bunch of addresses, some are online and some are not. I can't seem to get around this error however, even catching the exception fails :(
dns_get_record(): A temporary server error occurred.
try {
$result = dns_get_record('_minecraft._tcp.' . $addr, DNS_SRV);
}
catch (Exception $e) {
return [$addr,$port];
}
If this error occurs, I want to continue the script, skipping the record, however currently the script just halts.
Any help appreciated!!
I can't catch this exception too. And how I understood it's a bug of php:
https://bugs.php.net/bug.php?id=73149
But I found another solution. You can use # when you call this function. This symbol kill all errors when you call this one. And it will looks like that:
$dns = #dns_get_record($domain, DNS_A);
if(!$dns){
return false;
}
I was able to get the IP (A record) for a host using the below PHP function
gethostbynamel(string $hostname): array|false
Reference: gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name
try this:
try {
$dns = dns_get_record($domain, DNS_A);
}
catch (Exception $e) {
if ($e->getMessage() !== 'dns_get_record(): A temporary server error occurred.') {
throw $e;
}
$dns = false;
}
I want to stop code execution (all application code). Actually I manage this code:
try
{
$connection = mysqli_connect( $this->_host,
$this->_username,
$this->_dbPass,
$this->_dbName );
if(mysqli_connect_errno())
{
throw new Exception("problem in connection.");
}
}
catch(Exception $ex)
{
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
echo json_encode(array("success" => false, "message" => $ex->getMessage()));
return; //<- application don't end
//exit(); //<- application end
}
Now if I call another method after the above code block that prints "hello world" with the return statement I get the echo, but if I use exit() I don't see any echo. So my question is: throw a new exception don't stop the application instance? I must use exit() for stop it after the exception instead of return?
There has been quite a discussion in the comments, but to answer the question at hand, a return does stop execution of the script in the global scope.
http://sandbox.onlinephpfunctions.com/code/59a49286b1cbb62e92fd95134593c2da5ef94468
Example:
<?php
try {
throw new Exception('Hello');
}
catch (Exception $e) {
return;
}
echo "hello world"; // Not reached
?>
An exception will stop execution if it is uncaught. Otherwise, if the exception is caught, the same rules apply. In the global scope, return will exit the application, inside a function or method, a return will only exit the function.
exit() or die() will both exit the application no matter what scope they are called in.
Couchbase keeps complaining that I don't have a connection to Couchbase:
2013-10-28T11:15:46.580320-07:00 hoot77 apache2[30455]: PHP Warning: There is no active connection to couchbase in /ebs1/www/src/core/components/In/Couchbase/Bucket.php on line 112
The following is the piece of code that is trying to run, its a simple set.
*/
public function set($key, $doc, $try = 0) {
// Make sure designDoc and dataView are set
if(empty($this->designDoc) && empty($this->dataView)) {
throw new In_Exception('Missing Design Doc and/or View name for Couchbase', 400);
}
try {
$results = $this->cb->set($key, $doc);
} catch(CouchbaseLibcouchbaseException $e) {
// Connection not active, try to rebuild connection and query again
// Log stats on exception
Statsd::increment("web.Couchbase.Exception.LibCouchbaseException.{$this->instanceKey}");
Logger::error("LibCouchbaseException on {$this->instanceKey}: {$e->getMessage()}");
// Try to reconnect and query up to twice
$try++;
if($try <= 2) {
$this->rebuildConnection();
return $this->set($key, $doc, $try);
} else {
// Fail if we've already tried twice
throw new In_Exception('Could not connect to Couchbase', 500);
}
} catch(CouchbaseException $e) {
// Catch general exception, try to determine cause
// Log stats on exception
Statsd::increment("web.Couchbase.Exception.CouchbaseException.{$this->instanceKey}");
Logger::error("CouchbaseException on {$this->instanceKey}: {$e->getMessage()}");
// Throw exception if design document or view not found
if($this->getExceptionCode($e->getMessage()) == 404) {
throw new In_Exception('Design Document, or View not found in Couchbase', 404);
} else {
throw new In_Exception('Error with Couchbase, try again.', 500);
}
}
// Success, return results
Statsd::increment("web.couchbase.{$this->instanceKey}.success");
return $results;
}
The line that its complaining about is:
$results = $this->cb->set($key, $doc);
You can see that my quick solution was to try to reconnect up to twice on failure, but that doesn't seem to be helping at all, the errors still persist in great numbers.
It's actually not catching the exceptions and reporting them consistently either, which is annoying, because PHP is throwing these as warnings, not exceptions.
Let me know if you have any suggestions as to how to solve this, it would be greatly appreciated. Thanks!
I know this is a weird on, but in my code, i have development mode errors, and production mode errors. This is the function i have:
private function error($message, $mysql_error = null){
if( DEVELOPMENT_MODE ){
$exp = new Exception();
$trace = $exp -> getTrace();
array_shift( $trace ); // removes this functions from trace
$data["Error Mg"] = $message;
$data["MySQL Er"] = ( is_null ( $mysql_error ) ) ? "" : $mysql_error;
array_unshift($trace, $data );
fkill( $trace ); // formats array and then dies
}
else{
throw new Exception ( $data );
}
}
I wrote this function in my database class, so that if an error happens, I don't have to provide the check if we're in development mode or not!
So I thought I could externalise the re-usable code. However, because I'm throwing an exception from this function, I'm basically just using a function, that will return a thrown error. Pretty useless in production mode.
I would have to do this every time i want to use it:
try{
$this -> error( "Invalid Link After Connect.", mysql_error () );
} catch ( Exception $exp ){
throw $exp;
}
RATHER THAN JUST
$this -> error( "Invalid Link After Connect.", mysql_error () );
so to avoid writing a try ... catch block for every error function I want to call... is there any way to throw the exception 2 levels up?
An exception will automatically travel up the call chain until it reaches the highest level. If it's not caught there, program execution terminates due to an uncaught exception. The whole point of exceptions is to be able to have errors bubble up. You don't need to throw harder or do anything special to "throw it up 2 levels", that's what it does by definition.
Just omit the try/catch block. Exceptions automatically propagate up as far as they can until something catches them; you don't need to explicitly re-throw them at every level of the call stack.
This...
try{
$this -> error( "Invalid Link After Connect.", mysql_error () );
} catch ( Exception $exp ){
throw $exp;
}
is exactly equivalent to this:
$this -> error( "Invalid Link After Connect.", mysql_error () );
Use Multiple catch Blocks
use admin table which has field
Mode Value
0 Production
1 Debug
the first catch which matches the exception is executed
Example
try {
if (!$bDBConnection && $row['mode'] ==0 ) {
throw new Produciton_DBException("Problem with Database");
}
else
{
throw new Debug_DBException("Problem with Database");
}
}
catch(Produciton_DBException $e)
{
// display suitable error messages
}
catch(Debug_DBException $ex)
{
// Exception falls through until a match is found
}