I want to build a fully Swift error handling and propagation system that I can use throughout an entire application. The implementation is fairly straightforward, if you have something like this:
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
}
I can get the type of the error in a delegate function like this using a simple switch statement:
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")
}
}
However, I have the additional data from a particular case in the error enum
and that's when the problems arise:
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
}
How should I get the description
string from the Error type if I call the delegate method with a .networkError
?
As an extension, if there is no straightforward way to directly get the description
from a .networkError
, should I continue using the current architecture where the delegate method has an optional (nullable) Error type where I can check for the type of the error, or should I use a completely different architecture such as a try-catch system and if so, how should I implement it?