logger = $logger; $this->environment = env("APP_ENV", 'prod'); } public function handle(Throwable $throwable, ResponseInterface $response): ResponseInterface { // 判断被捕获到的异常是希望被捕获的异常 if ($throwable instanceof BusinessException) { if ($this->environment != "dev"){ // 生产环境 固定返回服务器错误 $message = HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR); }else{ $message = $throwable->getMessage(); } $generator = $this->container->get(IdGeneratorInterface::class); $id = $generator->generate(); $data = json_encode([ 'data' => $id, 'code' => $throwable->getCode(), 'message' => $message, ], JSON_UNESCAPED_UNICODE); $this->logger->error($id . "-start"); $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile())); $this->logger->error($throwable->getTraceAsString()); $this->logger->error($id . "-end"); // 阻止异常冒泡 $this->stopPropagation(); return $response->withStatus(500)->withHeader('content-type', 'application/json; charset=utf-8')->withBody(new SwooleStream($data)); } // 交给下一个异常处理器 return $response; // 或者不做处理直接屏蔽异常 } /** * 判断该异常处理器是否要对该异常进行处理 */ public function isValid(Throwable $throwable): bool { return true; } }