developeruz/yii2-custom-errorhandler

为 Yii 2.x 应用程序定制的错误处理器

1.0.0 2015-09-24 07:36 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:26:24 UTC


README

该模块允许将自定义处理程序附加到异常(Exception)。

###需要的情况### 例如,用于捕获用户“危险”操作。当出现错误时,您可以记录数据并跟踪特定用户或IP的 ForbiddenHttpException 或 NotFoundHttpException 的频率。这样,可以及时阻止用户并/或向管理员报告应用程序被攻击的尝试。使用模块的最简单方法是,在捕获 ForbiddenHttpException 时检查用户是否已登录,如果没有,则将其重定向到登录页面。

###安装:###

$ php composer.phar require developeruz/yii2-custom-errorhandler "*"

###配置:###

  • 在应用程序配置中指定在出现错误时调用的 action。
 'components' => [
 ...
    'errorHandler' => [
       'errorAction' => 'site/error',
    ],
 ...
  • 配置上一步中指定的 action。以我的示例为例,我在 site 控制器中编写。
 public function actions()
    {
        return [
            'error' => [
                'class' => 'developeruz\yii2_custom_errorhandler\ErrorHandler',
                'array_of_exceptions' => [
                    403 => function()
                    {
                        return $this->redirect(Url::to('/site/login'));
                    }, 
                    500 => function()
                    {
                        //send notification to administrator 
                        ...
                        return $this->redirect(Url::to('/site/index'));
                    }, 
                ]
            ]
        ];
    }

现在,当用户出现 ForbiddenHttpException 时,将重定向到登录页面。如果 array_of_exceptions 中没有描述错误处理,则它将由参数 $defaultErrorAction(默认为 yii\web\ErrorAction)指定的 ErrorAction 处理。