getLandId(); $toolItemId = $data->getUserItemId() ?? 0; // 铲除工具ID,可选 $userId = $this->user_id; // 先进行验证,避免不必要的事务开销 $validation = new CropRemoveValidation([ 'user_id' => $userId, 'land_id' => $landId, 'tool_item_id' => $toolItemId ]); // 验证数据 $validation->validated(); // 验证通过后,开启事务 DB::beginTransaction(); // 调用铲除作物服务 $result = CropService::removeCrop($userId, $landId); if (!$result) { throw new LogicException("铲除作物失败,请检查土地状态"); } // 如果使用了工具,消耗工具 if ($toolItemId > 0) { ItemService::consumeItem($userId, $toolItemId, null, 1, [ 'source_type' => 'land_remove_crop', 'source_id' => $landId, 'details' => ['land_id' => $landId] ]); } // 提交事务 DB::commit(); // 设置响应状态 $this->response->setCode(0); $this->response->setMsg('铲除作物成功'); Log::info('用户铲除作物成功', [ 'user_id' => $userId, 'land_id' => $landId, 'tool_item_id' => $toolItemId ]); } catch (\UCore\Exception\ValidateException $e) { // 验证失败,此时可能还没有开启事务 $this->response->setCode(400); $this->response->setMsg($e->getMessage()); Log::warning('铲除作物验证失败', [ 'user_id' => $userId ?? null, 'land_id' => $landId ?? null, 'tool_item_id' => $toolItemId ?? null, 'error' => $e->getMessage() ]); } catch (LogicException $e) { // 业务逻辑异常,需要回滚事务 if (DB::transactionLevel() > 0) { DB::rollBack(); } $this->response->setCode(400); $this->response->setMsg($e->getMessage()); Log::warning('用户铲除作物失败', [ 'user_id' => $userId ?? null, 'land_id' => $landId ?? null, 'tool_item_id' => $toolItemId ?? null, 'error' => $e->getMessage() ]); } catch (\Exception $e) { // 系统异常,需要回滚事务 if (DB::transactionLevel() > 0) { DB::rollBack(); } $this->response->setCode(500); $this->response->setMsg('系统错误,请稍后再试'); Log::error('铲除作物操作异常', [ 'user_id' => $userId ?? null, 'land_id' => $landId ?? null, 'tool_item_id' => $toolItemId ?? null, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); } return $response; } }