官术网_书友最值得收藏!

Error handling

Swift provides support to throw, catch, propagate, and manipulate recoverable errors at runtime.

Value types should conform to the Error protocol to be represented as errors. The following example presents some 4xx and 5xx HTTP errors as enum:

enum HttpError: Error { 
case badRequest
case unauthorized
case forbidden
case requestTimeOut
case unsupportedMediaType
case internalServerError
case notImplemented
case badGateway
case serviceUnavailable
}

We will be able to throw errors using the throw keyword and mark functions that can throw errors with the throws keyword.

We can use a do-catch statement to handle errors by running a block of code. The following example presents JSON parsing error handling in a do-catch statement:

protocol HttpProtocol{ 
func didRecieveResults(results: Any)
}

struct WebServiceManager {
var delegate:HttpProtocol?
let data: Data
func test() {
do {
let jsonResult = try JSONSerialization.jsonObject(with:
self.data, options: JSONSerialization.ReadingOptions
.mutableContainers)
self.delegate?.didRecieveResults(results: jsonResult)
} catch let error {
print("json error" + error.localizedDescription)
}
}
}

We can use a defer statement to execute a set of statements just before code execution leaves the current code block, regardless of how the execution leaves the current block of code.

主站蜘蛛池模板: 抚宁县| 崇明县| 资中县| 江安县| 绥江县| 乳源| 凉山| 剑川县| 嘉禾县| 德钦县| 华蓥市| 慈溪市| 鞍山市| 陆良县| 江门市| 寿光市| 溧阳市| 灌阳县| 文登市| 玛多县| 高雄县| 社旗县| 昭觉县| 宁南县| 乐清市| 济源市| 平安县| 大洼县| 宜都市| 荃湾区| 永年县| 阳曲县| 丹东市| 定州市| 西峡县| 枣庄市| 丽水市| 淅川县| 东至县| 商城县| 呼玛县|