// +---------------------------------------------------------------------- namespace app\adminapi; use crmeb\exceptions\AdminException; use crmeb\exceptions\ApiException; use crmeb\exceptions\AuthException; use think\db\exception\DbException; use think\exception\Handle; use think\exception\HttpResponseException; use think\exception\ValidateException; use think\facade\Env; use think\facade\Log; use think\Response; use Throwable; class AdminApiExceptionHandle extends Handle { /** * 不需要记录信息(日志)的异常类列表 * @var array */ protected $ignoreReport = [ ValidateException::class,//验证错误 DbException::class,//数据库错误 AuthException::class,//权限错误 AdminException::class,//后台错误 ApiException::class,//接口错误 ]; /** * 记录异常信息(包括日志或者其它方式记录) * @access public * @param Throwable $exception * @return void */ public function report(Throwable $exception): void { if (!$this->isIgnoreReport($exception)) { try { $data = [ 'file' => $exception->getFile(),//文件 'line' => $exception->getLine(),//行数 'message' => $this->getMessage($exception),//错误信息 'code' => $this->getCode($exception),//错误码 ]; //日志内容 $log = [ request()->adminId(), //管理员ID request()->ip(), //客户ip ceil(msectime() - (request()->time(true) * 1000)), //耗时(毫秒) request()->rule()->getMethod(), //请求类型 str_replace("/", "", request()->rootUrl()), //应用 request()->baseUrl(), //路由 json_encode(request()->param(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),//请求参数 json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), //报错数据 ]; Log::write(implode("|", $log), "error");//记录日志 } catch (\Throwable $e) { Log::write($e->getMessage(), "error");//记录日志 } } } /** * Render an exception into an HTTP response. * @access public * @param \think\Request $request * @param Throwable $e * @return Response */ public function render($request, Throwable $e): Response { // 如果是响应异常,直接返回 if ($e instanceof HttpResponseException) { return parent::render($request, $e);//直接返回 } // 调试模式下返回异常信息 $massageData = Env::get('app_debug', false) ? [ 'message' => $e->getMessage(),//错误信息 'file' => $e->getFile(),//文件 'line' => $e->getLine(),//行数 'trace' => $e->getTrace(),// 异常的追踪 'previous' => $e->getPrevious(),// 异常的上一个异常 ] : []; $message = $e->getMessage(); // 添加自定义异常处理机制 if ($e instanceof AuthException || $e instanceof AdminException || $e instanceof ApiException || $e instanceof ValidateException) { return app('json')->make($e->getCode() ?: 400, $message, $massageData); } else { return app('json')->fail($message, $massageData);//返回错误信息 } } }