关闭意外要求扔(Firebase)

时间:2017-07-18 21:13:31

标签: swift firebase error-handling firebase-realtime-database closures

所以我使用Firebase来拉取JSON并将其转换为function requestsPlot(plot, info) { const sqr = get(createSQRurl(plotObject.polygon)) .then(sqrHtmlParsing); const soilType = get(createSoilTypeUrl(plotObject.polygon)) .then(soilTypeHtmlParsing); const start = turf.centerOfMass(plotObject.polygon).geometry.coordinates; const end = info.homeCoords; const distance = get('http://router.project-osrm.org/route/v1/driving/' + start + ';' + end + '?overview=false') .then(JSON.parse); return Promise.all([sqr, soilType, distance]) .then(([parsedSqr, parsedSoilType, parsedDistance]) => Object.assign(plotObject, { quality: parsedSqr, soilType: parsedSoilType, distance: parsedDistance.code == 'Ok' ? parsed.routes[0].distance / 1000 : '' })) } 个对象的数组。

这是GasUse类。它的初始值设定项接受GasUse并在缺少键:值对时抛出错误。

Dictionary

然后我使用此代码创建class GasUse { let distance: Double let comment: String? let addedByUser: String let creationDate: Date init(from jsonDict: [String:Any]) throws { guard let distance = jsonDict["distance"] as? Double else { throw SerializationError.missing } let comment = jsonDict["comment"] as? String guard let addedByUser = jsonDict["addedByUser"] as? String else { throw SerializationError.missing } guard let creationDateString = jsonDict["creationDate"] as? String else { throw SerializationError.missing } self.distance = distance self.comment = comment self.addedByUser = addedByUser let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +zzzz" self.creationDate = dateFormatter.date(from: creationDateString)! } } 尝试

GasUse

但是这个函数似乎需要一个特定的格式来关闭它,我想我会遵循这个格式。

  

投掷类型'(_)抛出函数的转换无效 - > ()'到非投掷功能类型'(DataSnapshot) - >

中的Void'(rootSnapshot)

这里有什么问题?

1 个答案:

答案 0 :(得分:0)

编译器认为你的"尝试" block可能会抛出一些错误,这些错误不会被两个特定的" catch"说明。因此,从编译器的角度来看,你的闭包是一个投掷。要解决这个问题,只需添加一个可以捕获所有内容的第三个捕获:

do { let gasUse = try GasUse(from: value) }
catch SerializationError.missing { self.present(self.makeAlert("Error", "Missing value in json"), animated: true, completion: nil) }
catch SerializationError.invalid { self.present(self.makeAlert("Error", "Invalid value in json"), animated: true, completion: nil) }
catch error { 
    // print() or assert() if you want to control such a case
}