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

使用Alamofire.download()请求时如何从响应体获取错误信息

解决方案

核心原因说明

Alamofire的AFDownloadResponse默认确实没有直接提供data属性,因为下载请求默认是把响应内容写入本地文件而非保存在内存中,非200状态码走默认校验失败逻辑时,不会主动读取错误响应的内容。

方案1:使用responseData回调(适合小文件下载场景)

Alamofire的下载请求支持responseData方法,会自动把下载内容序列化为Data对象,无论成功失败都可以直接拿到响应体数据:

AF.download(url, parameters: params, to: destination)
  .validate(statusCode: [200])
  .responseData { response in
      switch response.result {
      case .success(_):
          // 下载成功,优先使用fileURL操作本地文件
          print("ok", response.fileURL ?? "")
      case .failure(let err):
          // 错误场景直接读取响应数据
          if let errData = response.data, let errMsg = String(data: errData, encoding: .utf8) {
              print("服务端错误:\(errMsg)")
          } else {
              print(err.localizedDescription)
          }
      }
  }

方案2:手动校验状态码(适合大文件下载场景)

如果下载的是大体积文件,避免把整个文件加载到内存,可以去掉默认的validate校验,自行判断状态码,仅在错误场景读取临时文件的错误内容:

AF.download(url, parameters: params, to: destination)
  .response { response in
      guard let statusCode = response.response?.statusCode else {
          print(response.error?.localizedDescription ?? "未知网络错误")
          return
      }
      
      if statusCode == 200, let fileURL = response.fileURL {
          // 正常下载成功逻辑
          print("ok", fileURL)
      } else {
          // 读取错误响应内容
          if let fileURL = response.fileURL, 
             let errData = try? Data(contentsOf: fileURL),
             let errMsg = String(data: errData, encoding: .utf8) {
              print("服务端错误:\(errMsg)")
          } else {
              print("Response status code was unacceptable: \(statusCode)")
          }
      }
  }

注意:大文件下载优先使用方案2,方案1会将整个下载内容加载到内存,可能引发内存溢出问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:24:04