2016-12-24 52 views
1

我想構建一個完整的Swift錯誤處理和傳播系統,我可以在整個應用程序中使用它。實現是相當簡單的,如果你有這樣的事情:Swift錯誤處理和錯誤的元數據

enum AnnouncerError: Error { 
    /// A network error occured 
    case networkError 
    /// The program was unable to unwrap data from nil to a non-nil value 
    case unwrapError 
    /// The parser was unable to validate the XML 
    case validationError 
    /// The parser was unable to parse the XML 
    case parseError 
} 

像這樣使用一個簡單的switch語句,我可以得到錯誤的類型的委託功能:

func feedFinishedParsing(withFeedArray feedArray: [FeedItem]?, error: AnnouncerError?) { 
    // unwrap the error somewhere here 
    switch error { 
    case .networkError: 
    print("Network error occured") 
    case .parseError: 
    print("Parse error occured") 
    case .unwrapError: 
    print("Unwrap error occured") 
    default: 
    print("Unknown error occured") 
    } 
} 

然而,我從錯誤enum特定情況下有更多的數據,這就是當問題出現:

enum AnnouncerError: Error { 
    /// A network error occured 
    case networkError(description: String) //note this line 
    /// The program was unable to unwrap data from nil to a non-nil value 
    case unwrapError 
    /// The parser was unable to validate the XML 
    case validationError 
    /// The parser was unable to parse the XML 
    case parseError 
} 

我應該如何得到description錯誤類型的字符串,如果我用.networkError調用委託方法?作爲擴展,如果沒有直接的方式從.networkError直接獲取description,我應該繼續使用當前的體系結構,其中委託方法有一個可選(可爲空)的錯誤類型,我可以在其中檢查錯誤還是應該使用完全不同的體系結構,如try-catch系統,如果是這樣,我應該如何實現它?

+0

可能相關:[附加數據的Swift 3錯誤](http://stackoverflow.com/questions/41202869/swift-3-errors-with-additional-data)和[如何提供本地化的描述與錯誤鍵入Swift?](http://stackoverflow.com/questions/39176196/how-to-provide-a-localized-description-with-an-error-type-in​​-swift)。 –

回答

2

如果您想訪問networkError案例的description財產,您不需要做太多的事情。

func feedFinishedParsing(withFeedArray feedArray: [FeedItem]?, error: AnnouncerError?) { 
    // unwrap the error somewhere here 
    switch error { 
    // Just declare description in the case, and use it if u need it. 
    case .networkError(let description): 
     print("Network error occured") 
     print(description) 
    case .parseError: 
     print("Parse error occured") 
    case .unwrapError: 
     print("Unwrap error occured") 
    default: 
     print("Unknown error occured") 
    } 
} 

當然,你可以建立一個強大的機器進行錯誤處理,但如果你只是想訪問這個屬性,上述解決方案將做的伎倆。

無論如何,我會推薦進一步閱讀Swift pattern matching,詳細解釋switch語言元素的高級用法是Swift