- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 186字
- 2021-07-02 23:54:30
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.
推薦閱讀
- 大數(shù)據(jù)可視化
- 數(shù)據(jù)庫(kù)開(kāi)發(fā)實(shí)踐案例
- Learning JavaScriptMVC
- 數(shù)據(jù)化網(wǎng)站運(yùn)營(yíng)深度剖析
- Sybase數(shù)據(jù)庫(kù)在UNIX、Windows上的實(shí)施和管理
- Oracle RAC日記
- Mastering LOB Development for Silverlight 5:A Case Study in Action
- 區(qū)塊鏈技術(shù)應(yīng)用與實(shí)踐案例
- Doris實(shí)時(shí)數(shù)倉(cāng)實(shí)戰(zhàn)
- 利用Python進(jìn)行數(shù)據(jù)分析(原書(shū)第2版)
- Access 2016數(shù)據(jù)庫(kù)應(yīng)用基礎(chǔ)
- Cognitive Computing with IBM Watson
- 區(qū)塊鏈應(yīng)用開(kāi)發(fā)指南:業(yè)務(wù)場(chǎng)景剖析與實(shí)戰(zhàn)
- Creating Mobile Apps with Appcelerator Titanium
- MySQL 8.0從入門(mén)到實(shí)戰(zhàn)