php - PDO的try/catch block 过多

标签 php error-handling pdo try-catch

在 Controller 类文件中,大多数方法函数都包含try/catch块,如下所示:

 try
   {
      $stmt = $this->prepare($sql);
      $stmt->execute($params);
      $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
      //foreach() or so on...
   }
   catch (Exception $e)
   {
      //bunch of code...
      //save error into database, etc.
      //error into json and pass to view file
   }

在catch块中有很多代码,有没有一种减少代码的方法。是否可以在catch块中添加“抛出异常”?

最佳答案

是的。自己尝试。您始终可以在catch块中抛出新的Exception或重新抛出相同的异常。

try
   {
      // ...
   }
   catch (Exception $e)
   {
      // do whatever you want
      throw new Your_Exception($e->getMessage());
      // or
      throw $e;
   }

关于php - PDO的try/catch block 过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7620305/

相关文章:

python - 如何在python中的子流程中使用错误处理

ios - 带有错误映射的 RestKit PUT 请求

php - 上载图片错误

php - PDO fetchAll 数组转为一维

php - 如何在本地主机上用php获取硬盘序列号

php - 回调函数在所有验证之前调用

php - 如何修复用户未以其在 PHP PDO 中指定的角色登录的问题

php - 使用 pdo php 将所有行作为对象获取

php - 带斜杠的 ZF2 路由参数

php - 使用 yii 框架切换到生产环境时出现 404