“无法到达捕获,因为没有对引发函数的调用”,但是函数引发错误?

时间:2019-07-18 11:07:12

标签: swift xcode alamofire

我可能会从Alamofire请求中收到SSL错误-1200,如果发生这种情况,我想将错误输出到文本字段。

我正试图捕捉到我在控制台窗口中遇到的错误,以便可以将其输出到文本字段,但是我从xcode获取此消息:

'catch' block is unreachable because no errors are thrown in 'do' block

这是我如何通过AF请求来构造do / try / catch:

do{
       try AF.request(host, method: .post, parameters: parameters, encoding:JSONEncoding.default)
           .responseData{ response in
               guard let responseData = response.data else { return }
               let responseJSON = try? JSON(data:responseData)
               if let responseJSONAsString = responseJSON?.rawString(){
                     self.output(text: responseJSONAsString + "\n\n\n")
               }
            }
}
catch {
        self.textField.stringValue = ("Caught: " + error.localizedDescription)
}

2 个答案:

答案 0 :(得分:1)

您需要

 AF.request(host, method: .post, parameters:parameters,encoding:JSONEncoding.default)
    .responseData { response in
        do {
            guard let responseData = response.data else { return }
            let responseJSON = try JSON(data:responseData)
            if let responseJSONAsString = responseJSON.rawString(){
                ///
            }
        }
        catch {
            print(error)
        }
   }

答案 1 :(得分:1)

Alamofire不会throw错误-这就是错误的意思-但您应该处理闭包中传递的错误

AF.request(host, method: .post, parameters: parameters, encoding: .default)
   .responseData { response in
       switch response.result {
       case .success(let data):
           do {
               let responseJSON = try JSON(data: data)
               if let responseJSONAsString = responseJSON?.rawString(){
                   self.output(text: responseJSONAsString + "\n\n\n")
               }
           } catch {
               self.textField.stringValue = ("Caught:", error.localizedDescription)
           }
       case .failure(let error): 
           self.textField.stringValue = ("Network Error:", error.localizedDescription)
       }
}