<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */

namespace app\api\exception;

use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\Log;
use think\Request;

/**
 * api接口的通用异常处理handle类
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2020/5/11
 * Time: 19:48
 */
class ExceptionHandler extends Handle
{
    public function render(Exception $e)
    {
        // 重写render方法
        if (\think\App::$debug) {
            return parent::render($e);
        } else {
            if ($e instanceof HttpException) {
                if ($e->getStatusCode() == 404) {
                    return json(["code" => 0, "msg" => "404 not found", "time" => time()]);
                }
                Log::error($e->getStatusCode() . " error, " . $e->getMessage());
                Log::error('请求数据 ' . var_export(Request::instance()->param(), true));
//            Log::error($e->getTraceAsString());//不记录HTTP异常(避免受一些攻击的影响写入大量日志)
            } else {
                Log::error("未知错误 " . $e->getMessage());
                Log::error("请求数据 " . var_export(Request::instance()->param(), true));
                Log::error($e->getTraceAsString());
                return json(["code" => 0, "msg" => "未知错误", "time" => time()]);
            }
        }
    }
}