46 lines
1.7 KiB
PHP
46 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace app;
|
|
|
|
use app\common\exception\UnauthorizedException;
|
|
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 UnauthorizedException) {
|
|
$json = json_encode(['code' => 401, 'msg' => $exception->getMessage()], JSON_UNESCAPED_UNICODE);
|
|
return new Response(401, ['Content-Type' => 'application/json'], $json);
|
|
} elseif ($exception instanceof BusinessException) {
|
|
return json(['code' => 0, 'msg' => $exception->getMessage(), 'show' => 1]);
|
|
} 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();
|
|
}
|
|
$json = json_encode($error, JSON_UNESCAPED_UNICODE);
|
|
return new Response(200, ['Content-Type' => 'application/json'], $json);
|
|
}
|
|
// 非json请求则返回一个页面
|
|
return new Response(200, [], 'msg:' . $exception->getMessage() . '。line:' . $exception->getLine() . '。file:' . $exception->getFile());
|
|
}
|
|
}
|