2016-05-25 120 views
3

我試圖處理RunTimeException通過SSH連接到VPS。我無法處理SSH連接錯誤

下面是通過SSH連接VPS的代碼。

$server_ip = Input::get('server_ip'); 
$password = Input::get('password'); 

$validator = Validator::make(
    ['server_ip' => $server_ip], 
    ['server_ip' => 'ip|required|unique:servers'], 
    ['password' => $password], 
    ['password' => 'required|confirmed'] 
); 

if(!$validator->fails()) 
{ 
    Config::set('remote.connections.production.host',$server_ip); 
    Config::set('remote.connections.production.username','root'); 
    Config::set('remote.connections.production.password',$password); 
    Config::set('remote.connections.production.root','/'); 

    $command = 'mysql --version'; 

    $connection_status = SSH::run($command, function($line) 
    { 
     $this->output = $line.PHP_EOL; 
    }); 

    if(!$connection_status) 
     return $this->output; 
    else 
     return view('dashboard.add_server'); 
} 
else 
    return "Validation failed..."; 

這是寫在Laravel。萬一,如果我的SSH連接出錯,它應該重定向到查看名爲add_server。但是,我得到異常而不是重定向。這裏是我每次都會遇到的錯誤,而不是重定向。

enter image description here

我要的是,如果有一些錯誤的連接通過SSH到VPS,它應該重定向我查看名爲add_server

讓我知道什麼是錯的代碼。

回答

3
try 
{ 
    $connection_status = SSH::run($command, function($line) 
    { 
     $this->output = $line.PHP_EOL; 
    }); 

    if(!$connection_status) 
     return $this->output; 
} 
catch(\RunTimeException $e) 
{ 
    return view('dashboard.add_server'); 
} 
1

您應該使用try-catch

try 
{ 
    $connection_status = SSH::run($command, function($line) 
    { 
     $this->output = $line.PHP_EOL; 
    }); 

    if(!$connection_status) 
     return $this->output; 
} 
catch(RunTimeException $e) 
{ 
    return view('dashboard.add_server'); 
} 

我不知道是否$connection_status應該得到成功連接後,假值,但是,除此之外,它應該工作。

+0

我試過這段代碼。不過,我得到了同樣的異常,但沒有重定向。 –