第 57 课2026.09.21
让关闭失败的用户看到可重试信息。
第 57 课:关闭失败时显示提示
- 日期:2026-09-21
- 课程序号:第 57 课
- 知识点:关闭失败时显示提示
用途或适用场景
让关闭失败的用户看到可重试信息。
核心概念
失败提示是纯界面反馈;关闭仍由 handle 执行,catch 设置通用提示并记录失败日志,finally 恢复进行中状态。
最小代码或操作示例
ts
@State closing: boolean = false
@State errorMessage: string = ''
async close(): Promise<void> {
if (this.closing || this.handle.isClosed()) return
this.closing = true
try { await this.handle.close() }
catch {
this.errorMessage = '关闭失败,请重试'
console.error('Handle.close failed')
} finally { this.closing = false }
}
build() {
Column() {
Button(this.handle.isClosed() ? '已关闭' : this.closing ? '关闭中…' : '关闭')
.enabled(!this.closing && !this.handle.isClosed())
.onClick(() => { this.close() })
if (this.errorMessage.length > 0) { Text(this.errorMessage) }
}
}3~5 分钟练习
让 handle.close() 拒绝一次并观察界面。
参考答案
按钮恢复可点击,提示显示“关闭失败,请重试”,日志保留错误详情。
与上一课的联系
沿用第 56 课的 handle、closing 状态与禁用逻辑;本课只新增 errorMessage、catch 日志和失败 Text;完成练习后下一课可让按钮明确标识重试动作。
时效校验
时效校验:2026-09-24(华为当前 Button、Text 官方文档;本机 HarmonyOS 26.0.0/API 26 SDK)。Button、Text 自 API 7 可用,相关声明未见 @deprecated 或 @useinstead。