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

Swift中如何将Alamofire返回的AFError错误转换为字符串值

AFError 转字符串解决方案

Alamofire 定义的AFError类型默认遵守 Swift 标准库的CustomStringConvertible、LocalizedError协议,可直接通过内置属性获取可读的错误字符串:

  • 展示给普通用户优先使用localizedDescription:返回系统适配本地化的友好错误提示
  • 开发调试排查问题使用description:返回包含错误类型、触发原因、关联上下文的详细调试信息
  • 自定义错误处理逻辑可使用errorDescription:LocalizedError协议提供的可选类型错误描述,可按需解包使用

修复后的代码示例

session.request("https://localhost:3000/my-route", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
    switch response.result {
    case .success(let result):
          print("nice", result)                         
        
    case .failure(let err):
        // 直接取内置属性赋值给String类型变量
        self.error = err.localizedDescription
        print("failure", err.description) // 控制台打印详细调试信息
    }
}

可选:精细化定制错误提示

如果需要针对不同错误场景返回自定义文案,可直接枚举AFError的匹配项:

case .failure(let err):
    switch err {
    case .sessionTaskFailed(let error as URLError) where error.code == .notConnectedToInternet:
        self.error = "当前网络不可用,请检查网络设置后重试"
    case .responseValidationFailed(let reason) where reason == .unacceptableStatusCode(code: 404):
        self.error = "请求的资源不存在"
    default:
        self.error = err.localizedDescription
    }

内容的提问来源于stack exchange,提问作者Evan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 01:36:09