Search code examples
swiftclosuresalamofire

How to throw Error and return value from ResponseString Alamofire


I have a question on throwing errors and returning values from ResponseString Alamofire. In fact, I think this is a problem with specified closures as parameter functions

enter image description here

func makeRequest() async throws -> String {
    AF.request("https://example.com")
        .validate()
        .responseString { response in
            switch response.result {
                case .success(let id):    return id
                case .failure(let error): throw APIErrors.alamoFireError(error)
            }
        }
}

How would I go about


Solution

  • Alamofire's response handlers (the various response* methods) don't support additional error handling. But that's not your fundamental issue, as you're trying to use a completion handler in an async context, which isn't going to work anyway. I suggest you use Alamofire's async handling instead.

    func makeRequest() async throws -> String {
      let result = await AF.request("https://example.com")
        .validate()
        .result
     
      switch result {
      case .success(let id):    return id
      case .failure(let error): throw APIErrors.alamoFireError(error)
      }
    }