Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-09-19

Code sample: Throwing an NSError to OS-X

NSError is used in document based app's to inform the OS about errors that occurred while opening or saving data (and in other places as well).
Since the OS will attempt to inform the user with a popup about the error, it is good practise to provide actual useful information in the thrown error such that the user sees more than "app X has thrown error 16"

Here an example on how to do this for the readFromData function.

override func readFromData(data: NSData, ofType typeName: String) throws {
                        
        if let fileAsString = NSString(bytes: data.bytes, length: data.length, encoding: NSUTF8StringEncoding) as? String {
                        
            // do stuff ....
            
        } else {
            
            let errorDict = [
                NSLocalizedDescriptionKey : "Could not convert the file data to a UTF8 string. (File at path = \(fileURL?.path))",
                NSLocalizedRecoverySuggestionErrorKey: "Try to open the file in TextEdit to see if it does contain text."
            ]

            let error = NSError(
               domain: Globals.errorDomain,
               code: Globals.errorCode_cannotRetrieveFileAsString, userInfo: errorDict)
            throw error
        }

    }

The fileURL is defined in NSDocument and can be used to get the URL of the file that is being openend.

The popup dialogue that is provided to the user uses the two key's in the errorDict to retrieve information from the error. (NSLocalizedDescriptionKey and NSLocalizedRecoverySuggestionErrorKey) There are more key's, but these two are the one's you should provide as a minimum.

It is customary to provide the errorDomain in backward URL notation, eg: "com.mycompany.MyGreatApp.ErrorDomain" the code can be any number within this error domain.

If you do not provide an errorDict, OS-X will create an localized description from the error domain and code number.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment