| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace App\Module\AppGame\Handler\House;
- use App\Module\AppGame\Handler\BaseHandler;
- use App\Module\Farm\Services\HouseService;
- use App\Module\Farm\Validations\HouseUpgradeValidation;
- use Google\Protobuf\Internal\Message;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Uraus\Kku\Request\RequestHouseUp;
- use Uraus\Kku\Response\ResponseHouseUp;
- use UCore\Exception\LogicException;
- /**
- * 处理房屋升级请求
- */
- class UpHandler extends BaseHandler
- {
- /**
- * 是否需要登录
- *
- * @var bool
- */
- protected bool $need_login = true;
- /**
- * 处理房屋升级请求
- *
- * @param RequestHouseUp $data 房屋升级请求数据
- * @return ResponseHouseUp 房屋升级响应
- */
- public function handle(Message $data): Message
- {
- // 创建响应对象
- $response = new ResponseHouseUp();
- try {
- $userId = $this->user_id;
- // 先进行验证,避免不必要的事务开销
- $validation = new HouseUpgradeValidation([
- 'user_id' => $userId
- ]);
- // 验证数据
- $validation->validated();
- // 验证通过后,开启事务
- DB::beginTransaction();
- // 执行业务逻辑(不再需要验证)
- $result = HouseService::executeHouseUpgrade($userId);
- if (!$result) {
- throw new LogicException("升级房屋失败");
- }
- // 提交事务
- DB::commit();
- // 记录成功日志
- Log::info('用户房屋升级成功', [
- 'user_id' => $userId
- ]);
- } catch (\UCore\Exception\ValidateException $e) {
- // 验证失败,此时可能还没有开启事务
- throw new LogicException($e->getMessage());
- } catch (LogicException $e) {
- // 业务逻辑异常,需要回滚事务
- if (DB::transactionLevel() > 0) {
- DB::rollBack();
- }
- Log::warning('用户房屋升级失败', [
- 'user_id' => $userId,
- 'error' => $e->getMessage()
- ]);
- throw $e;
- } catch (\Exception $e) {
- // 系统异常,需要回滚事务
- if (DB::transactionLevel() > 0) {
- DB::rollBack();
- }
- Log::error('用户房屋升级系统异常', [
- 'user_id' => $userId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- throw new LogicException('系统异常,请稍后重试');
- }
- return $response;
- }
- }
|