<?php

namespace common\components;

use Yii;
use yii\web\ErrorHandler;
use yii\web\Response;

class AjaxErrorHandler extends ErrorHandler
{

    /**
     * @param $exception
     * @return void
     */
    protected function renderException($exception)
    {
        if (Yii::$app->has('response')) {
            $response = Yii::$app->getResponse();
            $response->isSent = false;
        } else {
            $response = new Response();
        }
        $response->format = Response::FORMAT_JSON;
        $error_code = $exception->getCode();
        if ($exception->getCode() == 0) {
            $error_code = 1;
        }
        if ($exception instanceof AjaxException) {
            $msg = $exception->getMessage();
        } else {
            error_log($exception->getMessage());
            error_log($exception->getTraceAsString());
            $msg = "系统繁忙请稍后重试";
            var_dump($exception->getMessage());
            var_dump($exception->getTraceAsString());
            exit;
        }
        $response->data = [
            'r' => $error_code,
            'msg' => $msg
        ];
        $response->setStatusCode(200);
        $response->send();
    }

}
