You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 08:21:58