【问题标题】:Multiple try catch php Database多次尝试捕获php数据库
【发布时间】:2014-12-12 02:18:30
【问题描述】:

所以我想做的是在单个页面上尝试一次。这样做的原因是我正在运行我的代码的服务器似乎不喜欢多个尝试捕获。所以我想知道我应该在我的代码中插入什么来捕获数据库连接错误以及查询错误。我的代码对于这个页面来说有点长,所以我尽量缩短它,并且仍然有我所有的 try catch。错误页面工作得很好。我觉得我唯一的问题是扣子的位置

这是我到目前为止所得到的......

try{

    $db = @mysqli_connect('xxxx', 'xxxx', 'xxxx', 'xxxx');

        if(!$db){
        throw new aException(mysqli_connect_error());  
    }

    $strSQL = "SELECT * FROM blah blah blah";
    $result = mysqli_query($db, $strSQL);
    if(!$result){
        throw new bException(mysqli_error($db));  
    }

    $row = mysqli_fetch_array($result);

    echo '<select name="customer">';
    $custSQL = "select blah blah blah";
    $rs=mysqli_query($db,$custSQL);
    if(!$rs){
        throw new cException(mysqli_error($db));  
    }
     while($row=mysqli_fetch_array($rs)){ 

        if($row['cust_id'] == $customer){

            echo '<option selected="selected" value="'.$row[2].'">'.$row['cust_fname']. " " .$row['cust_lname'].'</option>';
        }
        else{
            echo '<option value="'.$row[2].'">'.$row['cust_fname']. " " .$row['cust_lname'].'</option>';
    }

        }

    mysqli_close($db);
    unset($db);

}catch(aException $e){ 

    header("Location: error.php?msg=" . $e->getMessage() . "&line=" . $e->getLine());
}
catch(bException $e){ 

    header("Location: error.php?msg=" . $e->getMessage() . "&line=" . $e->getLine());
}
catch(cException $e){ 

    header("Location: error.php?msg=" . $e->getMessage() . "&line=" . $e->getLine());
}

【问题讨论】:

  • 您似乎已经拥有它们? throw new whatever 是引发异常的代码。所以catch whatever 拿起它。
  • 好吧,我还有几个与前 3 个相同的异常,这是我在代码中为异常“致命错误:类 'fException' 不在第 209 行的 /www/virtualhosts/www.wat.com/group4/editorder2.php 中找到“
  • @elephantCoder , 这些是自定义异常吗?
  • 您需要使用 fException 扩展 Exception(这是您自己添加到现有代码中的?)
  • 不,我只是添加了aException,bException,cException,因为我认为抛出一个新的异常必须命名不同

标签: php exception-handling database-connection try-catch


【解决方案1】:

您可以在创建异常时使用接口。

interface myExceptionInterface{}

class aException extends \Exception implements myExceptionInterface {}
class bException extends \Exception implements myExceptionInterface {}
class cException extends \Exception implements myExceptionInterface {}

并使用此接口捕获它。

try{
    throw new bException;
}catch(myExceptionInterface $e){ 
    header("Location: error.php?msg=" . $e->getMessage() . "&line=" . $e->getLine());
}

附:在同一个范围内抛出和捕获异常有异味。

【讨论】:

  • 好吧,所以我试了一下,得到 500 内部服务器错误!我应该在这里发布我的整个代码吗?因为我不太确定 myExceptionInterface 是做什么的,而且我知道我没有在我的代码中正确添加它
  • 你应该探索你的错误。尝试查找您的 Web 服务器的 error.log。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-06
  • 2011-06-08
  • 2011-03-21
  • 2014-05-11
  • 2013-07-12
  • 1970-01-01
相关资源
最近更新 更多