<?php

namespace app;

use hg\apidoc\exception\ErrorException;
use Next\VarDumper\Dumper;
use Next\VarDumper\DumperHandler;
use support\exception\BusinessException;
use support\exception\Handler;
use support\Log;
use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;

class ExceptionHandler extends Handler
{

    use DumperHandler;

    public function render(Request $request, Throwable $exception): Response
    {
        if ($exception instanceof Dumper) {
            return \response(self::convertToHtml($exception));
        }elseif ($exception instanceof BusinessException) {
            if ($request->expectsJson()) {
                Log::error('BusinessException:',['msg'=>$exception->getMessage(),'file'=>$exception->getFile(),'line'=>$exception->getLine()]);
                return json(['code' => 0, 'msg' => $exception->getMessage(),'show'=>1]);
            }
            return response($exception->getMessage());
        } elseif ($exception instanceof \Exception) {
            $isDebug = config('app.debug');
            $error = [
                'code' => $isDebug ? $exception->getCode() : 0,
                'msg' => $isDebug ? $exception->getMessage() : '服务器内部错误',
            ];
            if ($isDebug) {
                $error['file'] = $exception->getFile();
                $error['line'] = $exception->getLine();
            }
            Log::error('Exception:',['msg'=>$exception->getMessage(),'file'=>$exception->getFile(),'line'=>$exception->getLine()]);
            return response(json_encode($error, JSON_UNESCAPED_UNICODE));
        }
        // 非json请求则返回一个页面
        Log::error('other:',['msg'=>$exception->getMessage(),'file'=>$exception->getFile(),'line'=>$exception->getLine()]);

        return new Response(200, [], 'msg:'.$exception->getMessage().'。line:'.$exception->getLine().'。file:'.$exception->getFile());
    }
}