UpHandler.php 2.7 KB

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