123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- <?php
- namespace app;
- use app\dict\sys\AppTypeDict;
- use core\exception\AdminException;
- use core\exception\AuthException;
- use core\exception\ServerException;
- use think\db\exception\DataNotFoundException;
- use think\db\exception\DbException;
- use think\db\exception\ModelNotFoundException;
- use think\exception\Handle;
- use think\exception\HttpException;
- use think\exception\HttpResponseException;
- use think\exception\ValidateException;
- use think\facade\Log;
- use think\Response;
- use Throwable;
- use UnexpectedValueException;
- class ExceptionHandle extends Handle
- {
-
- protected $ignoreReport = [
- HttpException::class,
- HttpResponseException::class,
- ModelNotFoundException::class,
- DataNotFoundException::class,
- ValidateException::class,
- ];
-
- public function report(Throwable $e): void
- {
-
- if (!$this->isIgnoreReport($e)) {
- $data = [
- 'file' => $e->getFile(),
- 'line' => $e->getLine(),
- 'message' => $e->getMessage(),
- 'trace' => $e->getTrace(),
- 'previous' => $e->getPrevious(),
- ];
-
- $app_type = request()->appType() ;
- $app_type = empty($app_type) ? str_replace('/', '', request()->rootUrl()) : $app_type;
-
- $log = [
- '服务主体:'.($app_type == AppTypeDict::ADMIN ? request()->uid() : request()->memberId()),
- 'IP:'.request()->ip(),
- '耗时(毫秒):'.ceil((microtime(true) * 1000) - (request()->time(true) * 1000)),
- '请求类型:'.request()->method(),
- '应用:'.$app_type,
- '路由:'.request()->baseUrl(),
- '请求参数:'.json_encode(request()->param() ?? []),
- '错误信息:'.json_encode($data),
- ];
- Log::write('DEBUG:>>>>>>>>>'.PHP_EOL.implode(PHP_EOL, $log).PHP_EOL.'---------', 'error');
- }
- }
-
- public function render($request, Throwable $e): Response
- {
-
- $massageData = env('app_debug', false) ? [
- 'file' => $e->getFile(),
- 'line' => $e->getLine(),
- 'message' => $e->getMessage(),
- 'trace' => $e->getTrace(),
- 'previous' => $e->getPrevious(),
- ] : [];
-
- if (strpos($e->getMessage(), 'open_basedir') !== false) {
- return fail('OPEN_BASEDIR_ERROR');
- }
- if ($e instanceof DbException) {
- return fail(get_lang('DATA_GET_FAIL').':'.$e->getMessage(), [
- 'file' => $e->getFile(),
- 'line' => $e->getLine(),
- 'message' => $e->getMessage(),
- 'trace' => $e->getTrace(),
- 'previous' => $e->getPrevious(),
- ]);
- } elseif ($e instanceof ValidateException) {
- return fail($e->getMessage());
- } else if($e instanceof UnexpectedValueException){
- return fail($e->getMessage(), [], 401);
- }else if($e instanceof AuthException){
- return fail($e->getMessage(), [], $e->getCode() ?: 400);
- }else if($e instanceof ServerException){
- return fail($e->getMessage(), http_code:$e->getCode());
- }else {
- return fail($e->getMessage(), $massageData);
- }
- }
- }
|