Skip to content

Instantly share code, notes, and snippets.

@florieger
Last active May 27, 2025 15:25
Show Gist options
  • Save florieger/50205f96fa9a9705c4fc161b39495fa4 to your computer and use it in GitHub Desktop.
Save florieger/50205f96fa9a9705c4fc161b39495fa4 to your computer and use it in GitHub Desktop.
Swift Error handling, bridging the gap between Error and NSError.
import Foundation
public typealias ACError = NSError
extension ACError {
public convenience init(message: String) {
var infoDict = [String: Any]()
infoDict[NSLocalizedDescriptionKey] = message
self.init(domain: "com.appcron", code: 0, userInfo: infoDict)
}
public var message: String {
// Use localizedDescription instead in infoDict,
// since some CoreData errors have a localizedDescription but no entry in the dictionary.
localizedDescription
}
}
extension Error {
public var message: String {
if let errorWithMessage = self as? ErrorWithMessage {
errorWithMessage.message
} else {
// Error can always be cast to NSError
(self as NSError).message
}
}
}
// This protocol enables other structs of Type Error to override the message property.
public protocol ErrorWithMessage {
var message: String { get }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment