【问题标题】:Yii2: How to use exceptions?Yii2:如何使用异常?
【发布时间】:2019-01-22 13:09:31
【问题描述】:

我想创建一个异常来稍微改进我的代码,但我不知道如何捕捉它。

我用 Yii2 框架的 find() 函数有一个简单的例子(所以我可以理解)。

Persons::find()
    ->select([
        'id',
        'name',
    ])
    ->all();

我想知道如果find() 函数无法完成,例如由于数据库服务器出现问题而无法访问数据库,如何获取错误信息。那么我可以做w3schools 教的事情。

【问题讨论】:

  • 在查询中出现语法错误或违反约束可以通过简单地将查询调用包装在try 中并使用catch 块在session->flash 中显示错误来处理,但如果错误是相关的到数据库连接,那么您可能必须使用errorHandler 组件中的errorAction

标签: php exception yii2 crud


【解决方案1】:

您可以简单地使用已回答的 try catch。

你可以参考这个文档来看看你有什么样的选项来抛出异常

https://www.yiiframework.com/doc/api/2.0/yii-db-exception

 try{
        $models = Persons::find()
            ->select([
                'id',
                'name',
            ])
            ->all();
    }catch(\yii\db\Exception $e){
        echo $e->getName(); 
    //Get the user-friendly name of this exception
    }

您还可以选择获取错误行号或错误代码

$e->getCode()
$e->getLine()

你也可以像下面这样使用 try catch 和 finally

try
    {

    }
    catch(Exception $e)
    {

    }
    finally
    {
        // to do something in common like close your file handler in this case, or some resource in general
    }

【讨论】:

    【解决方案2】:

    如下图使用try catch:

    根据您的情况,我使用了 DbException:

     try{
            $models = Persons::find()
                ->select([
                    'id',
                    'name',
                ])
                ->all();
        }catch(\yii\db\Exception $e){
            var_dump($e->getMessage()); //Get the error messages accordingly.
        }
    

    https://releasebits.blogspot.com/2018/08/using-exceptions-yii2.html

    【讨论】:

      猜你喜欢
      • 2015-04-13
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多