articles icon indicating copy to clipboard operation
articles copied to clipboard

Problem with LocalizedError, RecoverableError, CustomNSError final step on macOS

Open RickyRomero opened this issue 4 years ago • 0 comments

https://github.com/NSHipster/articles/blob/master/2019-03-18-swift-foundation-error-protocols.md#improving-interoperability-with-cocoa-error-handling-system

I ran into a problem where despite following the macOS error-handling tutorial and adding the CustomNSError protocol, I still wasn't able to get the dialog box to display the error text and message. The extension DelegatingRecoverableError: CustomNSError snippet doesn't account for all the properties in the customNSError protocol. However, even when I added those (returning data from (self.error as NSError)), the error message still didn't appear correctly.

I resolved this by conforming to the LocalizedError protocol instead. Despite the article asserting that it's more work, it wasn't that much more work, and more importantly fixed the issue I had.

extension DelegatingRecoverableError: LocalizedError {
    var errorDescription: String? {
        return (self.error as NSError).userInfo[NSLocalizedDescriptionKey] as? String
    }
    var failureReason: String? {
        return (self.error as NSError).userInfo[NSLocalizedFailureReasonErrorKey] as? String
    }
    var helpAnchor: String? {
        return (self.error as NSError).userInfo[NSHelpAnchorErrorKey] as? String
    }
    var recoverySuggestion: String? {
        return (self.error as NSError).userInfo[NSLocalizedRecoverySuggestionErrorKey] as? String
    }
}

RickyRomero avatar May 25 '20 04:05 RickyRomero