fix(manager): fix initialization order to prevent nil pointer panic#422
Conversation
Move initAgent() call before initDbusSignalListen() in NewManager() to ensure userAgents is initialized before session signals are connected. Also add defensive nil checks in handleSessionNew and handleSessionRemoved as a safety measure. Bug: https://pms.uniontech.com/bug-view-361789.html
|
CLA Assistant Lite bot: |
deepin pr auto review你好!我是CodeGeeX。我已仔细审查了你提供的Git Diff代码。本次修改主要涉及将 整体来看,这次修改的逻辑是合理的,解决了对象初始化顺序可能导致的空指针问题,并增加了防御性编程。但仍有几个方面可以进一步优化,以下是详细的审查意见: 1. 语法与逻辑评价: 逻辑清晰,修改意图明确。
改进建议:
2. 代码质量评价: 代码可读性较好,但防御性检查存在代码重复。 改进建议:
3. 代码性能评价: 本次修改对性能没有负面影响。 改进建议:
4. 代码安全评价: 增加了空指针检查,提升了系统的健壮性和安全性。 改进建议:
综合改进后的代码示例基于以上建议,我为你重构了相关代码,主要优化了日志级别、消除了重复的防御性检查,并增强了代码的健壮性: manager.go 修改部分: // NewManager 内部
func NewManager(service *dbusutil.Service, updateApi system.System, c *config.Config) (*Manager, error) {
// ... 其他代码 ...
go func() {
m.setPropHardwareId(updateplatform.GetHardwareId(m.config.IncludeDiskInfo, m.config.GetHardwareIdByHelper))
}()
// 必须在监听 D-Bus 信号前初始化 userAgents,防止回调时出现空指针
m.initAgent()
if m.userAgents == nil {
// 核心组件初始化失败,记录严重错误。视业务严格程度,这里也可以考虑 return nil, errors.New("userAgents init failed")
logger.Error("userAgents failed to initialize, session management will be disabled")
}
m.initDbusSignalListen()
m.initDSettingsChangedHandle()
m.syncThirdPartyDconfig()
// ... 其他代码 ...
}
// 提取公共的检查方法,消除重复代码
func (m *Manager) isUserAgentsReady() bool {
if m.userAgents == nil {
// 提升日志级别,这是一个严重的异常状态
logger.Error("userAgents not initialized, skipping session operation")
return false
}
return true
}
func (m *Manager) handleSessionNew(sessionId string, sessionPath dbus.ObjectPath) {
// ... 获取 userInfo 逻辑 ...
uidStr := strconv.Itoa(int(userInfo.UID))
if !m.isUserAgentsReady() {
return
}
newlyAdded := m.userAgents.addSession(uidStr, session)
if newlyAdded {
m.watchSession(uidStr, session)
}
}
func (m *Manager) handleSessionRemoved(sessionId string, sessionPath dbus.ObjectPath) {
logger.Debug("session removed", sessionId, sessionPath)
if !m.isUserAgentsReady() {
return
}
m.userAgents.removeSession(sessionPath)
}通过以上调整,代码的健壮性、可维护性和错误可见性都得到了提升。如果有其他疑问,欢迎随时提问! |
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: qiuzhiqian, zhaohuiw42 The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
Move initAgent() call before initDbusSignalListen() in NewManager() to ensure userAgents is initialized before session signals are connected.
Also add defensive nil checks in handleSessionNew and handleSessionRemoved as a safety measure.
Bug: https://pms.uniontech.com/bug-view-361789.html