云功能发布请求未正确向 IOS 应用程序发送错误消息

问题描述

我有一个 iOS 应用从谷歌云函数接收 json 数据。

在没有错误的情况下检索数据并正常工作。

但是,当云函数返回错误时,下面的函数会将error 识别为nil

客户:

func initialize() {

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json",forHTTPHeaderField: "Content-Type")
        request.httpBody = try? JSONSerialization.data(withJSONObject: json)
        let task = URLSession.shared.dataTask(with: request,completionHandler: { [weak self] (data,response,error) in
            
            guard let response = response as? HTTPURLResponse,response.statusCode == 200,let data = data,let json = try? JSONSerialization.jsonObject(with: data,options: []) as? [String : Any],let clientSecret = json["clientSecret"] as? String,let publishableKey = json["publishableKey"] as? String else {
                
                ///////////   
               //ERROR is not being recognized
                /////////

           let message = error?.localizedDescription ?? "Failed to decode response from server."
           print("Error loading page: \(message)")
                    return
       }
})
task.resume()
}

客户端输出

无法解码来自服务器的响应。

服务器:

firebase.functions().httpsCallable('myFunction')(message)
    .then(result => {
    // this works perfectly and is recognized by the swift function //
    res.send({publishableKey: publishableKey,clientSecret: clientSecret});
})
.catch(err => {
    // this is not recognized by the swift function //
     console.log(err) // full of data
    return res.status(400).send({error: err});
});

日志(用于错误情况):

函数执行耗时 240 毫秒,完成状态码:400

解决方法

如果您的请求失败,我认为您的错误将进入响应参数,您必须对其进行解码。我认为仅当无法访问服务器或函数不存在时,错误参数才会与 nil 不同。所以基本上在 else 子句中,您将不得不搜索响应参数中的错误。