如何在Swift中处理带尾随闭包语法的抛出闭包?

问题描述 投票:0回答:3

我正在使用Alamofire来执行HTTP请求。

try Alamofire.request(url, headers: headers)
  .validate()
  .response { response in
    let error = response.error;

   if (error != nil) {
     throw MyError(message: "No good")
   }


   // This line is from Alamofire docs and causes no issue 
   let json = try! JSONSerialization.jsonObject(with: response.data!, options: [])

   // do more goodies here which may also throw exceptions
}

自从我添加了throw,我得到了错误Invalid conversion from throwing function of type '(_) throws -> ()' to non-throwing function type '(DefaultDataResponse) -> Void'。我以前得到过这个,并且知道我只需要在正确的位置添加try。我认为在Alamofire.request面前这样做可能会成功,但事实并非如此。

我也试过了

let req = Alamofire.request(url, headers: headers).validate();
try req.response { response in

当我搜索“扔在尾随封闭中”时,我找不到任何关于此的内容。

swift alamofire
3个回答
0
投票

问题是你传递给Alamofire的关闭是不允许扔的。如果你问自己“如果这个函数丢了谁会处理它?”这是有道理的。抛出你调用函数的范围是行不通的(也就是在try前添加一个Alamofire.request),因为在异步操作之后将调用闭包,你可能完全离开了作用域。如果Alamofire在你的关闭位置周围有一个do-catch区块,那就会打败让你首先投入的目的,因为Alamofire不知道如何处理你投掷的错误,只需要吃它(无用)或通过通过关闭或某种通知回复给你,现在我们已经走了一圈。在这种情况下,我认为解决问题的最佳方法是调用你在catch块中放置的任何东西来处理你想要的Alamofire.request抛出错误。

Alamofire.request(url, headers: headers)
  .validate()
  .response { response in
    let error = response.error;

   if (error != nil) {
     DaveSteinErrorHandler.handleError(MyError(message: "No good"))
   }


   // This line is from Alamofire docs and causes no issue 
   let json = try! JSONSerialization.jsonObject(with: response.data!, options: [])

   // do more goodies here
}

为了将来参考,在这种情况下,有一些术语和代码用于定义您编写的代码正在执行的行为。 rethrows关键字意味着您正在调用的函数将接受闭包作为参数,并且函数将抛出的唯一错误是来自您的抛出闭包的错误。


0
投票

您应该遵循do-try-catch语法。

所以,你应该做更像这样的事情:

do {
    try Alamofire.request(url, headers: headers)
    /* Rest of the try */
} catch {
    /* Runs if the `try` fails
}

该错误非常具有误导性。


0
投票

根据上面的评论,我不能直接抛出。我最终这样做了:

try Alamofire.request(url, headers: headers)
  .validate()
  .response { response in
    do {
      let error = response.error;

      if (error != nil) {
        throw MyError(message: "No good")
      }

      // more logic

      if (anotherCondition == true) {
        throw AnotherError(message: "Error Parsing return data that I expected");
      }

    }
    catch let error {
      uiMessage = "";
      if error is errorThatUserShouldSeeSomething {
        uiMessage = error.localizedDescription;
      }
      ErrorHandler.handle(error: error, uiMessage: uiMessage); 
    }
}

我老实说要去做ErrorHandler.handle电话,无论如何这是我的自定义处理程序。尽管如此,让它在堆栈中更高一点会更好。

© www.soinside.com 2019 - 2024. All rights reserved.