ErrorHandler.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace components;
  3. use Yii;
  4. use yii\base\UserException;
  5. use yii\web\Response;
  6. use yii\web\HttpException;
  7. use yii\web\ErrorHandler as baseErrorHandler;
  8. /**
  9. * 异常处理模型
  10. * Class ErrorHandler
  11. * @package components
  12. */
  13. class ErrorHandler extends baseErrorHandler
  14. {
  15. /**
  16. * 传递异常
  17. * @author: libingke
  18. * @param \Error|\Exception $exception
  19. */
  20. protected function renderException($exception)
  21. {
  22. if (Yii::$app->has('response')) {
  23. $response = Yii::$app->getResponse();
  24. $response->isSent = false;
  25. $response->stream = null;
  26. $response->data = null;
  27. $response->content = null;
  28. } else {
  29. $response = new Response();
  30. }
  31. $useErrorView = $response->format === Response::FORMAT_HTML && (!YII_DEBUG || $exception instanceof UserException);
  32. if ($useErrorView && $this->errorAction !== null) {
  33. $result = Yii::$app->runAction($this->errorAction);
  34. if ($result instanceof Response) {
  35. $response = $result;
  36. } else {
  37. $response->data = $result;
  38. }
  39. } elseif ($response->format === Response::FORMAT_HTML) {
  40. if (YII_ENV_TEST || isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
  41. $response->data = '<pre>' . $this->htmlEncode(static::convertExceptionToString($exception)) . '</pre>';
  42. } else {
  43. if (YII_DEBUG) {
  44. ini_set('display_errors', 1);
  45. }
  46. $file = $useErrorView ? $this->errorView : $this->exceptionView;
  47. $response->data = $this->renderFile($file, [
  48. 'exception' => $exception,
  49. ]);
  50. }
  51. } elseif ($response->format === Response::FORMAT_RAW) {
  52. $response->data = static::convertExceptionToString($exception);
  53. } else {
  54. $response->data = static::convertExceptionToArray($exception);
  55. }
  56. if ($exception instanceof HttpException) {
  57. $response->setStatusCode($exception->statusCode);
  58. } else {
  59. $response->setStatusCode(200);
  60. }
  61. if (is_array($response->data)) {
  62. //$response->data['error'] = $response->data['name'];
  63. unset($response->data['name'], $response->data['type']);
  64. ksort($response->data);
  65. $response->data['data'] = [];
  66. }
  67. $response->send();
  68. }
  69. }