【问题标题】:Custom error handler for any exception任何异常的自定义错误处理程序
【发布时间】:2012-12-02 21:27:47
【问题描述】:

问题是我按照这个主题 http://www.yiiframework.com/doc/guide/1.1/en/topics.error 做所有事情,但是当在我的控制器中我引发异常( throw new Exception("error"); )时,yii 不要路由到我的自定义错误控制器并使用系统默认值.如何处理此类异常?

【问题讨论】:

    标签: php exception-handling yii


    【解决方案1】:

    你必须使用 Yii 自己的异常类之一:CExceptionCDbExceptionCHttpException。从您提供的链接:http://www.yiiframework.com/doc/guide/1.1/en/topics.error#raising-exceptions

    // if post ID is invalid
    throw new CHttpException(404,'The specified post cannot be found.');
    

    【讨论】:

    • 我知道这种情况,但是如果mysql抛出异常(例如错误的查询或类似的事情)?
    【解决方案2】:

    如果 mysql 出现异常,请运行您的查询

    $insertCommand = $model->getCommandBuilder()->createSqlCommand($sql,$baseParams+$relParams);
    try {
            $insertCommand->execute();
    } catch(CDbException $e) {
            // Here's a way to get to the error code for the statement in question.
            // These codes are standardized ANSI SQL "SQLSTATE" error codes.
            $sqlErrorCode = $insertCommand->pdoStatement->errorCode();
            // And to get to the class part of it, simple grab the two first characters.
            // The class should be the same regardless of DB vendor, while the rest of the code can differ.
            // For example one particular error was reported by PostgreSQL as 23505 but MySQL only said 23000.
            $sqlErrorCodeClass = substr($sqlErrorCode, 0, 2);
    }
    

    【讨论】:

    • 对于每一个查询我必须写try catch?
    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 2014-05-28
    • 2019-12-20
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多