12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- <?php
- namespace components;
- use Yii;
- use yii\base\UserException;
- use yii\web\Response;
- use yii\web\HttpException;
- use yii\web\ErrorHandler as baseErrorHandler;
- /**
- * 异常处理模型
- * Class ErrorHandler
- * @package components
- */
- class ErrorHandler extends baseErrorHandler
- {
- /**
- * 传递异常
- * @author: libingke
- * @param \Error|\Exception $exception
- */
- protected function renderException($exception)
- {
- if (Yii::$app->has('response')) {
- $response = Yii::$app->getResponse();
- $response->isSent = false;
- $response->stream = null;
- $response->data = null;
- $response->content = null;
- } else {
- $response = new Response();
- }
- $useErrorView = $response->format === Response::FORMAT_HTML && (!YII_DEBUG || $exception instanceof UserException);
- if ($useErrorView && $this->errorAction !== null) {
- $result = Yii::$app->runAction($this->errorAction);
- if ($result instanceof Response) {
- $response = $result;
- } else {
- $response->data = $result;
- }
- } elseif ($response->format === Response::FORMAT_HTML) {
- if (YII_ENV_TEST || isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
- $response->data = '<pre>' . $this->htmlEncode(static::convertExceptionToString($exception)) . '</pre>';
- } else {
- if (YII_DEBUG) {
- ini_set('display_errors', 1);
- }
- $file = $useErrorView ? $this->errorView : $this->exceptionView;
- $response->data = $this->renderFile($file, [
- 'exception' => $exception,
- ]);
- }
- } elseif ($response->format === Response::FORMAT_RAW) {
- $response->data = static::convertExceptionToString($exception);
- } else {
- $response->data = static::convertExceptionToArray($exception);
- }
- if ($exception instanceof HttpException) {
- $response->setStatusCode($exception->statusCode);
- } else {
- $response->setStatusCode(200);
- }
- if (is_array($response->data)) {
- //$response->data['error'] = $response->data['name'];
- unset($response->data['name'], $response->data['type']);
- ksort($response->data);
- $response->data['data'] = [];
- }
- $response->send();
- }
- }
|