SC #6:使用 async/await 的网络请求

发布: (2026年1月17日 GMT+8 23:05)
2 min read
原文: Dev.to

Source: Dev.to

示例代码

func performPOSTURLRequest() async throws(NetworkingError) -> PostData {
  do {
    let request = try buildURLRequest()
    let (data, response) = try await URLSession.shared.data(for: request)

    guard let statusCode = (response as? HTTPURLResponse)?.statusCode else {
      throw NetworkingError.invalidStatusCode(statusCode: -1)
    }

    guard (200..<300).contains(statusCode) else {
      throw NetworkingError.invalidStatusCode(statusCode: statusCode)
    }

    let decodedResponse = try JSONDecoder().decode(PostResponse.self, from: data)
    print("The JSON response contains a name: \(decodedResponse.json.name) and an age: \(decodedResponse.json.age)")

    return decodedResponse.json

  } catch let error as EncodingError {
    throw .encodingFailed(innerError: error)
  } catch let error as DecodingError {
    throw .decodingFailed(innerError: error)
  } catch let error as URLError {
    throw .requestFailed(innerError: error)
  } catch let error as NetworkingError {
    throw error
  } catch {
    throw .otherError(innerError: error)
  }
}

注意事项

  • 编译器会提示如果没有返回任何值,这在基于 closures 的实现中是不可能的。
  • 虽然代码的某些部分会抛出 NetworkingError 类型的错误,但必须显式捕获它们;否则会被通用的 catch 捕获。
  • URLSession.shared.data(for:) 在请求成功时返回 非可选 值;如果出现错误,则会抛出异常。
Back to Blog

相关文章

阅读更多 »

SC #4: async/await 语法

async/await 函数声明:异步函数必须使用关键字 async 标记。如果函数可能抛出错误,则添加关键字 catch……

SC #3:与 Swift 6 的关系

Swift Concurrency 3 部分系列 https://dev.to/david_goyes_a488f58a17a53/series/35092 “Swift Concurrency” 是 Swift 6 的基石,然而,Swift 6 的定义……