[swift 進階]讀書筆記-第八章:錯誤處理 C8P8 錯誤鏈 Chaining Errors

第八章:錯誤處理 Error Handling

8.8 錯誤鏈 Chaining Errors

本小節主要講了如何優雅的處理鏈式調用多個可能拋出錯誤的方法。swift

其實swift 的內建(build-in)錯誤處理處理機制就已經很好的將鏈式調用可能拋錯的方法,咱們直接用一個大的do/catch塊把這一段包裹住就行。
可是做爲一個優秀的開發者,咱們能夠用更優雅的解決方案去處理這種場景。

還記得以前學的Result類麼? 咱們能夠經過Result類去包裝返回值,讓你的代碼變得更加優雅 more elegant。ui

具體Demo以下spa

///未經過Result包裝error的檢查文件和返回pid的方法
func checkFilesAndFetchProcessID(filenames: [String]) -> Int {
     do {
    try filenames.all(checkFile)
        let contents = try contentsOfFile("Pidfile") 
        return try optional(Int(contents),
        orError: ReadIntError.CouldNotRead) }
     catch {
        return 42 // 默認值 
    }
}

///經過Result包裝error的檢查文件和返回pid的方法,毫無try catch 痕跡可言。 
func checkFilesAndFetchProcessID(filenames: [String]) -> Result<Int> { 
    return filenames
    . all (checkFile)
    .flatMap { _ in contentsOfFile("Pidfile") } 
    .flatMap { contents in
    Int ( contents).map(Result.Success) ?? .Failure(ReadIntError.CouldNotRead)
    } 
}
複製代碼
注: 這裏其實是經過一系列的flatMap方法去過濾掉error, 在實際開發中,咱們能夠經過一樣能夠經過flatmap作不少關於去除nil的騷操做, 這個知識點以前有聽過瞄神提過。 忘了具體使用場景,知道同窗們能夠補充分享。 Thx~
相關文章
相關標籤/搜索