getLandId(); $userId = $this->user_id; // 先进行验证,避免不必要的事务开销 $validation = new CropHarvestValidation([ 'user_id' => $userId, 'land_id' => $landId ]); // 验证数据 $validation->validated(); try { // 验证通过后,开启事务 DB::beginTransaction(); // 调用收获服务 $harvestResult = CropService::harvestCrop($userId, $landId); if ($harvestResult->error) { throw new LogicException($harvestResult->message ?: "收获失败,请检查土地状态或作物生长阶段"); } // 更新用户活动时间 $this->updateUserActivityTime(); // 提交事务 DB::commit(); Log::info('用户收获成功', [ 'user_id' => $userId, 'land_id' => $landId, 'harvest_result' => $harvestResult->data ?? [] ]); }catch (\Exception $e) { // 系统异常,需要回滚事务 if (DB::transactionLevel() > 0) { DB::rollBack(); } Log::error('收获操作异常', [ 'user_id' => $userId ?? null, 'land_id' => $landId ?? null, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); // 重新抛出异常,交由框架处理 throw $e; } return $response; } }