【问题标题】:Thrown exception, but how to catch it properly in PHP?抛出异常,但如何在 PHP 中正确捕获它?
【发布时间】:2016-08-24 06:55:49
【问题描述】:

我的问题是我在 PHP 中的类函数中有我自己定义的异常,我可以捕获它,但它以非常有趣的方式完全停止了页面呈现。 基本上,当异常被捕获时,页面不会呈现。相反,它只是给了我一串与我的期望完全不同的异常。 我有这个抛出异常的函数,我在子类的函数中捕获它,因为我不使用这个类本身,只是在子类中。

    function auth($username, $password) { 
    if(!ssh2_auth_password($this->ssh, $username, $password)) {
        throw new Exception('Invalid credentials');
        return false; 
    }

    $fingerprint = ssh2_fingerprint($this->ssh, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);

    if (!$fingerprint) {
        throw new Exception('No fingerprint');
        return false;
    }

    return $fingerprint; 
    } 

抛出的异常是“无效凭据”

调用该函数的子类函数

    try {
        $this->ssh->setupConnection($data['connectivity']['serverAdress'], $data['connectivity']['serverPort']);
        $fingerprint = $this->ssh->auth($data['connectivity']['serverLogin'], $data['connectivity']['serverPassword']);         
    } catch (Exception $e) {
        $this->errorAndLog("blah blah blah");
        return false;
    }

子类中的所有内容都正确继承,依此类推

如您所见,我在这里捕获了异常,但页面仍然没有呈现并以类似 var_dump 的样式显示我的异常:

string(18) "无效凭证"

我不确定是我没有弄清楚异常还是代码在某些时候有错误

UPD:对不起,出了点问题。类不是子父类。具有auth() 函数的类被包含在带有

的“主”类中
public function __construct()
{
    $this->ssh = new SSH2();
}

【问题讨论】:

  • catch (Exception $e) { throw new Exception($e->getMessage()); } 或 catch (Exception $e) { throw new Exception('blah blah blah'); }?
  • @Hendra Nucleo 什么?

标签: php exception try-catch


【解决方案1】:

解决了。只需重新编写代码即可正常工作而不会引发异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-13
    • 2019-12-28
    • 1970-01-01
    • 2016-08-20
    • 2015-10-09
    • 2013-05-07
    • 2020-10-03
    • 1970-01-01
    相关资源
    最近更新 更多