swift - 'Catch 无法访问,因为没有调用抛出函数',但函数抛出错误?

标签 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)
}

最佳答案

你需要

 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)
        }
   }

关于swift - 'Catch 无法访问,因为没有调用抛出函数',但函数抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57093093/

相关文章:

ios - 如何成功传递字符串数组作为参数 alamofire

swift - 插入或拔出耳机时 AVAudioEngine 崩溃

swift - 进度指示器没有动画

iphone - ViewController 在 iOS6 上不旋转

ios - 使用 SwiftyJSON 处理 JSON 响应

ios - Alamofire 帖子正文格式不正确

swift - 使用 Alamofire 通过发布请求传递 token

ios - 如何使用 Swift (IOS) 实现可拖动的 MKPointAnnotation?

ios - pushViewController 不推送新 View

ios - 通过从应用程序商店下载的同一个应用程序从 Xcode 安装 iOS 应用程序(反之亦然)