<?php
namespace app\common\exception;

use app\hander\HelpHander;
use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;

class Http extends Handle
{
	public function render(Exception $e)
	{
		// 参数验证错误
		if ($e instanceof ValidateException) {
		    $this->error('请求错误');
		}
		
		// 请求异常
		if ($e instanceof HttpException && request()->isAjax()) {
            $this->error('请求异常');
		}

        $this->error($e->getMessage());
	}

    private function error($msg, $code = 1, $data = [])
    {
        $code = $code == 0 ? 1 : $code; // code不能等于0
        if($data){
            $data = array_change_line_to_hump($data);
        }
        $json = [
            'code' => $code,
            'message' => $msg,
            'data' => $data
        ];

        header('Content-Type:application/json; charset=utf-8');
        if(version_compare(PHP_VERSION,'5.4.0','<')){
            exit(json_encode($json));
        }else{
            exit(json_encode($json,JSON_UNESCAPED_UNICODE)); //显示中文
        }
    }
}