Is it possible to determine which error matched the pattern in a catch statement? Also, is it possible to get any associated value(s) with the error that was matched?
Determine error matching pattern in catch?
In the catch statement you can use a switch/case statement to look for a specific error type. I have created an errors generator example that you can place into playgrounds to see the switch/case pattern in use.
/**
Errors Example code by Sean Batson (MobileTen)
*/
import Foundation
enum GenericErrors: Error {
case offline, certificates
}
extension GenericErrors: LocalizedError {
var errorDescription: String? {
switch self {
case .offline:
return "Server responded out of disk space"
case .certificates:
return "Certificates expired 24 hours ago"
}
}
}
enum ForumQuestionErrors: Error {
case answered, none
}
extension ForumQuestionErrors: LocalizedError {
var errorDescription: String? {
switch self {
case .answered:
return "Question previously answered limit reached"
case .none:
return "Ok"
}
}
}
class Forums {
let error = [offlineGenericError, certsGenericError, answeredForumError, noneForumError]
func generateError() {
let method = error[Int.random(in: 0..<error.count)]
do {
try method(self)()
} catch {
switch error {
case is GenericErrors:
print(error, error.localizedDescription)
case is ForumQuestionErrors:
print(error, error.localizedDescription)
default:
print(error, error.localizedDescription)
}
}
}
func offlineGenericError() throws {
throw GenericErrors.offline
}
func certsGenericError() throws {
throw GenericErrors.certificates
}
func answeredForumError() throws {
throw ForumQuestionErrors.answered
}
func noneForumError() throws {
throw ForumQuestionErrors.none
}
}
let forum = Forums()
forum.generateError()