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; } }