getPetId(); $skillIds = $data->getSkillId(); // RepeatedField,包含多个技能ID $userId = $this->user_id; // 将RepeatedField转换为数组 $skillIdArray = []; foreach ($skillIds as $skillId) { $skillIdArray[] = $skillId; } // 技能参数(暂时使用默认值) $params = []; Log::info('用户批量使用宠物生活技能', [ 'user_id' => $userId, 'pet_id' => $petId, 'skill_ids' => $skillIdArray, 'skill_count' => count($skillIdArray) ]); // 验证参数 if (!$petId || $petId <= 0) { throw new LogicException("宠物ID无效"); } if (empty($skillIdArray)) { throw new LogicException("技能ID列表不能为空"); } // 验证技能ID foreach ($skillIdArray as $skillId) { if (!$skillId || $skillId <= 0) { throw new LogicException("技能ID无效: {$skillId}"); } } // 开启事务 DB::beginTransaction(); $successCount = 0; $failedSkills = []; $errorMessages = []; // 逐个激活技能 foreach ($skillIdArray as $skillId) { try { // 调用宠物服务使用技能 $result = PetService::useSkill($userId, $petId, $skillId, $params); $successCount++; Log::info('单个技能激活成功', [ 'user_id' => $userId, 'pet_id' => $petId, 'skill_id' => $skillId ]); } catch (\Exception $e) { $failedSkills[] = $skillId; $errorMessages[] = "技能{$skillId}: " . $e->getMessage(); Log::warning('单个技能激活失败', [ 'user_id' => $userId, 'pet_id' => $petId, 'skill_id' => $skillId, 'error' => $e->getMessage() ]); } } // 如果有失败的技能,抛出异常说明情况 if (!empty($failedSkills)) { $errorMsg = "部分技能激活失败:" . implode('; ', $errorMessages); if ($successCount === 0) { // 全部失败 throw new LogicException("所有技能激活失败:" . implode('; ', $errorMessages)); } else { // 部分失败,记录警告但不抛出异常 Log::warning('部分技能激活失败', [ 'user_id' => $userId, 'pet_id' => $petId, 'success_count' => $successCount, 'failed_count' => count($failedSkills), 'error_message' => $errorMsg ]); } } // 提交事务 DB::commit(); Log::info('宠物生活技能批量使用完成', [ 'user_id' => $userId, 'pet_id' => $petId, 'total_skills' => count($skillIdArray), 'success_count' => $successCount, 'failed_count' => count($failedSkills), 'failed_skills' => $failedSkills ]); } catch (\UCore\Exception\ValidateException $e) { // 验证失败 DB::rollBack(); Log::warning('宠物生活技能使用验证失败', [ 'user_id' => $this->user_id, 'pet_id' => $petId ?? null, 'skill_id' => $skillId ?? null, 'error' => $e->getMessage() ]); throw $e; } catch (LogicException $e) { // 业务逻辑异常 if (DB::transactionLevel() > 0) { DB::rollBack(); } Log::warning('宠物生活技能使用失败', [ 'user_id' => $this->user_id, 'pet_id' => $petId ?? null, 'skill_id' => $skillId ?? null, 'error' => $e->getMessage() ]); throw $e; } catch (\Exception $e) { // 系统异常 if (DB::transactionLevel() > 0) { DB::rollBack(); } Log::error('宠物生活技能使用异常', [ 'user_id' => $this->user_id, 'pet_id' => $petId ?? null, 'skill_id' => $skillId ?? null, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); throw $e; } return $response; } }