Swift標準庫解析:協(xié)議篇 - Error

Error協(xié)議是用來進行錯誤處理的。
源碼如下:

public protocol Error {
}

extension Error {
    //錯誤的本地化描述
    public var localizedDescription: String { get }
}

extension Error where Self.RawValue : SignedInteger {
}

extension Error where Self.RawValue : UnsignedInteger {
}

可以看到,標準庫中只提供了一個localizedDescription只讀屬性呕屎,用來描述錯誤的具體信息磺陡。除此之外趴梢,并沒有其他的方法。

Apple官方推薦使用枚舉類型币他,具體說明如下坞靶。
Swift's enumerations are well suited to represent simple errors. Create an enumeration that conforms to the Error protocol with a case for each possible error. If there are additional details about the error that could be helpful for recovery, use associated values to include that information.

關(guān)于錯誤處理,我自己對這方面的了解的也不夠深蝴悉。這里我給大家介紹一下AlamofireAFError類彰阴,間接的來了解一下Error協(xié)議的用法。

定義

public enum AFError: Error {
    public enum ParameterEncodingFailureReason {
        case missingURL
        case jsonEncodingFailed(error: Error)
        case propertyListEncodingFailed(error: Error)
    }

    public enum MultipartEncodingFailureReason {
        case bodyPartURLInvalid(url: URL)
        case bodyPartFilenameInvalid(in: URL)
        case bodyPartFileNotReachable(at: URL)
        . . .
    }

    public enum ResponseValidationFailureReason {
        case dataFileNil
        case dataFileReadFailed(at: URL)
        case missingContentType(acceptableContentTypes: [String])
        . . .
    }

    public enum ResponseSerializationFailureReason {
        case inputDataNil
        case inputDataNilOrZeroLength
        case inputFileNil
        . . .
    }

    case invalidURL(url: URLConvertible)
    case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
    case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
    case responseValidationFailed(reason: ResponseValidationFailureReason)
    case responseSerializationFailed(reason: ResponseSerializationFailureReason)
}

每個case分別對應(yīng)一種錯誤類型拍冠,并關(guān)聯(lián)一個Reason尿这。
嵌套4個Reason枚舉簇抵,來對錯誤的原因再次進行分類。不得不說代碼很有邏輯感射众,也寫的很好看碟摆。

錯誤描述

extension AFError.ParameterEncodingFailureReason {
    var localizedDescription: String {
        switch self {
        case .missingURL:
            return "URL request to encode was missing a URL"
        case .jsonEncodingFailed(let error):
            return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
        case .propertyListEncodingFailed(let error):
            return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)"
        }
    }
}

extension AFError.MultipartEncodingFailureReason {
    var localizedDescription: String {
        switch self {
        case .bodyPartURLInvalid(let url):
            return "The URL provided is not a file URL: \(url)"
        case .bodyPartFilenameInvalid(let url):
            return "The URL provided does not have a valid filename: \(url)"
        case .bodyPartFileNotReachable(let url):
            return "The URL provided is not reachable: \(url)"
        . . .
        }
    }
}

extension AFError.ResponseSerializationFailureReason {
    var localizedDescription: String {
        switch self {
        case .inputDataNil:
            return "Response could not be serialized, input data was nil."
        case .inputDataNilOrZeroLength:
            return "Response could not be serialized, input data was nil or zero length."
        case .inputFileNil:
            return "Response could not be serialized, input file was nil."
        . . .
        }
    }
}

extension AFError.ResponseValidationFailureReason {
    var localizedDescription: String {
        switch self {
        case .dataFileNil:
            return "Response could not be validated, data file was nil."
        case .dataFileReadFailed(let url):
            return "Response could not be validated, data file could not be read: \(url)."
        case .missingContentType(let types):
            return (
                "Response Content-Type was missing and acceptable content types " +
                "(\(types.joined(separator: ","))) do not match \"*/*\"."
            )
        . . .
        }
    }
}

使用localizedDescription屬性,對每一個Reason的分支叨橱,進行詳細的描述典蜕。

當然了,AFError并不是只有這些內(nèi)容罗洗,還有很多方便我們使用的擴展等愉舔,由于它并不是我這篇文章的主要討論方向,就不做更多介紹了栖博。 有興趣的可以去看看下面這個參考鏈接屑宠。
http://www.reibang.com/p/99e6ba32f244

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市仇让,隨后出現(xiàn)的幾起案子典奉,更是在濱河造成了極大的恐慌,老刑警劉巖丧叽,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件卫玖,死亡現(xiàn)場離奇詭異,居然都是意外死亡踊淳,警方通過查閱死者的電腦和手機假瞬,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來迂尝,“玉大人脱茉,你說我怎么就攤上這事÷⒖” “怎么了琴许?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長溉躲。 經(jīng)常有香客問我榜田,道長,這世上最難降的妖魔是什么锻梳? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任箭券,我火速辦了婚禮,結(jié)果婚禮上疑枯,老公的妹妹穿的比我還像新娘辩块。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布庆捺。 她就那樣靜靜地躺著古今,像睡著了一般。 火紅的嫁衣襯著肌膚如雪滔以。 梳的紋絲不亂的頭發(fā)上捉腥,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天,我揣著相機與錄音你画,去河邊找鬼抵碟。 笑死,一個胖子當著我的面吹牛坏匪,可吹牛的內(nèi)容都是我干的拟逮。 我是一名探鬼主播,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼适滓,長吁一口氣:“原來是場噩夢啊……” “哼敦迄!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起凭迹,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤罚屋,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后嗅绸,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體脾猛,經(jīng)...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年鱼鸠,在試婚紗的時候發(fā)現(xiàn)自己被綠了猛拴。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡蚀狰,死狀恐怖愉昆,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情麻蹋,我是刑警寧澤跛溉,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站哥蔚,受9級特大地震影響倒谷,放射性物質(zhì)發(fā)生泄漏蛛蒙。R本人自食惡果不足惜糙箍,卻給世界環(huán)境...
    茶點故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望牵祟。 院中可真熱鬧深夯,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至掌呜,卻和暖如春滓玖,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背质蕉。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工势篡, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人模暗。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓禁悠,卻偏偏與公主長得像,于是被迫代替她去往敵國和親兑宇。 傳聞我的和親對象是個殘疾皇子碍侦,可洞房花燭夜當晚...
    茶點故事閱讀 44,614評論 2 353

推薦閱讀更多精彩內(nèi)容