Yii2:如何使用异常?

Yii2: How to use exceptions?

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

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

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

我想知道如果 find() 函数无法完成,例如由于数据库服务器出现问题而无法访问数据库,如何得到错误。这样我就可以做 w3schools 教的东西了。

使用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

您可以简单地使用已经回答过的 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 with finally

try
    {

    }
    catch(Exception $e)
    {

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