multi-store/app/ExceptionHandler.php

49 lines
1.9 KiB
PHP
Raw Normal View History

2024-05-30 21:37:55 +08:00
<?php
2024-06-03 17:28:23 +08:00
namespace app;
2024-05-30 21:37:55 +08:00
2024-06-03 11:03:08 +08:00
use hg\apidoc\exception\ErrorException;
2024-05-30 21:37:55 +08:00
use Next\VarDumper\Dumper;
use Next\VarDumper\DumperHandler;
2024-06-04 16:51:26 +08:00
use support\exception\BusinessException;
2024-05-30 21:37:55 +08:00
use support\exception\Handler;
use support\Log;
2024-05-30 21:37:55 +08:00
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]);
}
2024-06-04 16:51:26 +08:00
return response($exception->getMessage());
2024-06-03 16:14:59 +08:00
} elseif ($exception instanceof \Exception) {
$isDebug = config('app.debug');
$error = [
2024-06-03 17:28:23 +08:00
'code' => $isDebug ? $exception->getCode() : 0,
2024-06-03 16:14:59 +08:00
'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()]);
2024-06-03 16:14:59 +08:00
return response(json_encode($error, JSON_UNESCAPED_UNICODE));
2024-05-30 21:37:55 +08:00
}
// 非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());
2024-05-30 21:37:55 +08:00
}
}