lihaiMiddleOffice/app/ExceptionHandler.php

45 lines
1.5 KiB
PHP

<?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 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()) {
return json(['code' => 0, 'msg' => $exception->getMessage(),'show'=>1]);
}
return response($exception->getMessage());
} elseif ($exception instanceof \Exception) {
$isDebug = config('app.debug');
$error = [
'show' => 1,
'code' => $isDebug ? $exception->getCode() : 0,
'msg' => $isDebug ? $exception->getMessage() : '服务器内部错误',
];
if ($isDebug) {
$error['file'] = $exception->getFile();
$error['line'] = $exception->getLine();
}
return response(json_encode($error, JSON_UNESCAPED_UNICODE));
}
// 非json请求则返回一个页面
return new Response(200, [], 'msg:'.$exception->getMessage().'。line:'.$exception->getLine().'。file:'.$exception->getFile());
}
}