我在Laravel中编写了一个函数来测试SFTP与用户提供的服务器凭据的连接。此功能正常工作,并显示有关连接状态的相应消息。
public function testConnection(Request $request)
{
$data = $request->all();
$this->protocol = $data['protocol'];
$this->host = $data['domain_name'];
$this->username = $data['username'];
$this->password = $data['password'];
$this->port = $data['port'];
$returnData = $this->checkFtp();
return response()->json(['status' => true, 'connectionStatus' => $returnData]);
}
public function checkFtp()
{
// Variable initialization
$returnData = 'success';
// SFTP connection test
if ($this->protocol === 'sftp') {
$sftp = new SFTP($this->host, $this->port, $this->timeout);
if ($sftp) {
if (!$sftp->login($this->username, $this->password)) {
$returnData = 'Unable to login to the SFTP server';
}
} else {
$returnData = 'Unable to connect to SFTP server';
}
}
}
当用户提供无效主机时,会发生内部服务器错误。所以我无法在返回显示中收到消息。
如何获得正确的错误消息以回复此功能?
示例(提供实际凭证时)
{
"status":true,
"connectionStatus":"success"
}
内部服务器错误(给出错误的主机名或IP)
{
"message": "Cannot connect to invalid.host.com:22. Error 113. No route to host",
"exception": "ErrorException",
"file": "/var/www/html/rvhost_admin/vendor/phpseclib/phpseclib/phpseclib/Net/SSH2.php",
"line": 1139,
"trace": [
{
"function": "handleError",
"class": "Illuminate\\Foundation\\Bootstrap\\HandleExceptions",
"type": "->"
},
{
"file": "/var/www/html/rvhost_admin/vendor/phpseclib/phpseclib/phpseclib/Net/SSH2.php",
"line": 1139,
"function": "user_error"
},
{
"file": "/var/www/html/rvhost_admin/vendor/phpseclib/phpseclib/phpseclib/Net/SSH2.php",
"line": 2158,
"function": "_connect",
"class": "phpseclib\\Net\\SSH2",
"type": "->"
},
更新:我已经通过添加try-catch重写了该函数,但我仍然得到相同的错误...
// SFTP connection test
if ($this->protocol === 'sftp') {
try {
$sftp = new SFTP($this->host, $this->port, $this->timeout);
if ($sftp) {
if (!$sftp->login($this->username, $this->password)) {
$returnData = 'Unable to login to the SFTP server';
}
} else {
$returnData = 'Unable to connect to SFTP server';
}
} catch(Exception $e) {
$returnData = $e->getMessage();
}
}
我认为你可以在subscribe()中处理这个,如下所示。 500内部错误消息将出现'错误'。只需控制“错误”即可查看该消息
this.service.functionname(this.form.value).subscribe(data => {
console.log(data);
}, error => {
console.log(error);
});