UpHandler.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace App\Module\AppGame\Handler\House;
  3. use App\Module\AppGame\Handler\BaseHandler;
  4. use App\Module\Farm\Services\HouseService;
  5. use App\Module\Farm\Validations\HouseUpgradeValidation;
  6. use Google\Protobuf\Internal\Message;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. use UCore\Helper\Logger;
  10. use Uraus\Kku\Request\RequestHouseUp;
  11. use Uraus\Kku\Response\ResponseHouseUp;
  12. use UCore\Exception\LogicException;
  13. /**
  14. * 处理房屋升级请求
  15. */
  16. class UpHandler extends BaseHandler
  17. {
  18. /**
  19. * 是否需要登录
  20. *
  21. * @var bool
  22. */
  23. protected bool $need_login = true;
  24. /**
  25. * 处理房屋升级请求
  26. *
  27. * @param RequestHouseUp $data 房屋升级请求数据
  28. * @return ResponseHouseUp 房屋升级响应
  29. */
  30. public function handle(Message $data): Message
  31. {
  32. // 创建响应对象
  33. $response = new ResponseHouseUp();
  34. try {
  35. $userId = $this->user_id;
  36. // 先进行验证,避免不必要的事务开销
  37. $validation = new HouseUpgradeValidation([
  38. 'user_id' => $userId
  39. ]);
  40. // 验证数据
  41. $validation->validated();
  42. // 验证通过后,开启事务
  43. DB::beginTransaction();
  44. // 执行业务逻辑(不再需要验证)
  45. $result = HouseService::executeHouseUpgrade($userId);
  46. if (!$result) {
  47. throw new LogicException("升级房屋失败");
  48. }
  49. // 提交事务
  50. DB::commit();
  51. // 记录成功日志
  52. Log::info('用户房屋升级成功', [
  53. 'user_id' => $userId
  54. ]);
  55. } catch (\UCore\Exception\ValidateException $e) {
  56. // 验证失败,此时可能还没有开启事务
  57. throw new LogicException($e->getMessage());
  58. } catch (LogicException $e) {
  59. // 业务逻辑异常,需要回滚事务
  60. if (DB::transactionLevel() > 0) {
  61. DB::rollBack();
  62. }
  63. Log::warning('用户房屋升级失败', [
  64. 'user_id' => $userId,
  65. 'error' => $e->getMessage()
  66. ]);
  67. throw $e;
  68. } catch (\Exception $e) {
  69. // 系统异常,需要回滚事务
  70. if (DB::transactionLevel() > 0) {
  71. DB::rollBack();
  72. }
  73. Logger::error('用户房屋升级系统异常', [
  74. 'user_id' => $userId,
  75. 'error' => $e->getMessage(),
  76. 'trace' => $e->getTraceAsString()
  77. ]);
  78. throw new LogicException('系统异常,请稍后重试');
  79. }
  80. return $response;
  81. }
  82. }