yii1tech / error-handler
为Yii1应用程序提供增强的错误处理器
1.0.0
2024-04-24 13:59 UTC
Requires
- php: >=7.2
- yiisoft/yii: ~1.1.0
Requires (Dev)
- phpunit/phpunit: ^6.0 || ^7.0 || ^8.0 || ^9.3 || ^10.0.7
This package is auto-updated.
Last update: 2024-08-24 14:37:45 UTC
README
Yii1增强错误处理器
此扩展为Yii1应用程序提供增强的错误处理器。
有关许可证信息,请参阅LICENSE文件。
安装
安装此扩展的首选方式是通过composer。
运行
php composer.phar require --prefer-dist yii1tech/error-handler
或在您的composer.json中的"require"部分添加
"yii1tech/error-handler": "*"
。
用法
此扩展为Yii1应用程序提供增强的错误处理器。其主要功能是将PHP错误转换为异常,以便通过try..catch
块进行处理。
注意:为了使错误转换为异常的功能生效,应将错误处理器组件添加到应用程序的"preload"部分。
应用程序配置示例
<?php return [ 'preload' => [ 'errorHandler', // preload custom error handler, overriding the default one, allowing error to exception conversion // ... ], 'components' => [ 'errorHandler' => [ 'class' => \yii1tech\error\handler\ErrorHandler::class, ], // ... ], // ... ];
配置完成后,\yii1tech\error\handler\ErrorHandler
允许您将PHP错误作为异常捕获。例如
<?php try { // ... trigger_error('Some custom error message', E_USER_WARNING); // ... } catch (ErrorException $exception) { // handle error }
此外,\yii1tech\error\handler\ErrorHandler
提供了错误/异常以JSON格式输出的支持,这对于现代XHR和API实现非常有用。默认情况下,只有在HTTP客户端传递带有匹配MIME类型“application/json”的“Accept”头时,错误才会以JSON格式渲染。但是,您可以使用\yii1tech\error\handler\ErrorHandler::$shouldRenderErrorAsJsonCallback
来控制此行为。例如
<?php return [ 'preload' => [ 'errorHandler', // preload custom error handler, overriding the default one, allowing error to exception conversion // ... ], 'components' => [ 'errorHandler' => [ 'class' => \yii1tech\error\handler\ErrorHandler::class, 'shouldRenderErrorAsJsonCallback' => function () { if (!empty($_SERVER['HTTP_ACCEPT']) && strcasecmp($_SERVER['HTTP_ACCEPT'], 'application/json') === 0) { return true; } if (Yii::app()->request->isAjaxRequest) { return true; } if (str_starts_with(Yii::app()->request->getPathInfo(), 'api/')) { return true; } return false; }, ], // ... ], // ... ];
您可以在自定义错误操作中重用错误处理器将错误作为JSON渲染的能力,该操作通过\CErrorHandler::$errorAction
指定。例如
<?php class SiteController extends CController { public function actionError(): void { /** @var \yii1tech\error\handler\ErrorHandler $errorHandler */ $errorHandler = Yii::app()->getErrorHandler(); if ($errorHandler->shouldRenderErrorAsJson()) { // render JSON error representation. $errorHandler->renderErrorAsJson(); return; } // Render HTML error representation: if ($error = $errorHandler->error) { $this->render('error', $error); } } }