如何在iOS App Intents中抛出可被用户查看的错误?
解决AppIntents自定义错误无法在Shortcuts显示的问题
要让自定义错误在Shortcuts应用中正确展示给用户,仅实现LocalizedError是不够的,需要结合AppIntents框架的特定要求来处理:
定义合规的自定义错误类型
自定义错误需同时遵循Error、LocalizedError和AppIntentError协议,示例代码如下:enum IntentError: Error, LocalizedError, AppIntentError { case objectNotFound var errorDescription: String? { switch self { case .objectNotFound: return NSLocalizedString("无法找到指定对象,该对象可能已被删除。", comment: "对象不存在错误提示") } } var errorCategory: ErrorCategory { switch self { case .objectNotFound: return .failed } } }在perform方法中抛出错误
在Intent的perform()方法内,检测到CoreData对象不存在时直接抛出自定义错误:func perform() async throws -> some IntentResult { guard let targetObject = fetchCoreDataObject() else { throw IntentError.objectNotFound } // 正常业务逻辑处理 return .result(value: ...) }配置本地化文件
确保项目中存在Localizable.strings文件,且已添加对应错误描述的本地化条目,多语言环境下需为每种语言配置对应内容,确保Shortcuts能读取到正确的提示文本。关键注意点
- 必须实现
AppIntentError协议,仅靠LocalizedError无法让Shortcuts识别自定义错误描述 - 错误描述需使用用户易懂的表述,避免技术术语
- 必须实现
内容的提问来源于stack exchange,提问作者Sn0wfreeze
相关产品推荐
相关产品推荐

