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

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.

主站蜘蛛池模板: 苏尼特左旗| 沁阳市| 金溪县| 莲花县| 呼图壁县| 正定县| 青铜峡市| 临海市| 枣阳市| 安乡县| 五指山市| 綦江县| 漳平市| 黎城县| 尤溪县| 利辛县| 景德镇市| 彭阳县| 砚山县| 重庆市| 泾阳县| 重庆市| 华安县| 辽宁省| 尼勒克县| 那坡县| 调兵山市| 灵寿县| 本溪| 揭西县| 罗源县| 西安市| 武汉市| 永靖县| 鹿邑县| 基隆市| 柳河县| 台山市| 青河县| 吉林省| 上犹县|