2013-01-02 60 views
0

我正在使用this script here並且它並不總是想連接到我設置的服務器。如果沒有,則會顯示錯誤"Failed to receive status"。我想知道如何測試以查看是否發生這種情況並將其放入if語句中?測試連接是否爲錯誤

例如:

if (isError) return false; 

這裏是一個檢查錯誤或不執行腳本的一部分:

if(!$Data) 
     { 
      throw new MinecraftQueryException("Failed to receive status."); 
     } 

回答

3

只需使用try ... catch塊。但請確保您正在記錄異常消息。這將有助於未來的調查。

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; 
} 
+0

我在調用對象時能做到這一點嗎?例如,嘗試{echo $ cbMain-> GetInfo()['Players']} catch(error){}它是否在對象內部? – devs

+0

是的,在試塊中做所有正常的操作。 –

+0

@DEVS查看更新。另請參閱README.md https://github.com/xPaw/PHP-Minecraft-Query/blob/master/README.md –

1

你要圍繞try/catch塊內Connect調用,以捕獲異常,然後把故障代碼的catch塊。您可以在PHP manual中瞭解有關例外情況的更多信息:

try { 
    $query->Connect(); 
} catch(MinecraftQueryException $exception) { 
    return false; 
}