Search code examples
iosloggingerror-codecommoncrypto

Convert error codes to text in iOS


I have a wrapper for encrypting and decrypting using CommonCryptor. Occasionally the decryption process will fail, in which case I fill an error like so:

if (result == kCCSuccess) {
    cipherData.length = outLength;
} else {
    if (error) {
        *error = [NSError errorWithDomain:kBridgeEncryptorErrorDomain
                                     code:result
                                 userInfo:nil];
    }

    return nil;
}

And then I log the error like this:

if (error != nil) {
    DDLogError(@"Decrypt fail %i, %@", [error code], [error localizedDescription]);
}

However, this ends up generating strings like:

2013-01-09 09:15:19.753 [BridgeEncrypter decryptDataFromData:] [Line 83] E: Decrypt fail -4304, The operation couldn’t be completed. (com.***.bridgecrypt error -4304.)

Where the -4304 could be any of the error codes in CommonCryptor.h (-4300 to -4305). Is there a good way to map the error codes to their string values, or do I need to have a switch statement that adjusts the string by hand? If I do have to depend on a switch, would best practice be to put it where the issue is logged or where the error is generated?


Solution

  • I'm not sure what you're looking for here. I'm not familiar with CommonCryptor or how error messages are handled in it.

    I can recommend that you lean on NSError and it's userInfo and NSLocalized*Key feature.

    For example, if you set a NSLocalizedDescriptionKey in the userInfo dictionary, error:

    NSDictionary userInfo = @{
        NSLocalizedDescriptionKey : @"This is the error message I want users to see"
    };
    *error = [NSError errorWithDomain:kBridgeEncryptorErrorDomain
                                 code:result
                             userInfo:userInfo];
    

    Then This is the error message I want users to see is the string returned by -localizedDescription. Then the calling code can use the string to display a message to the user without needing to reinterpret it.

    As to the question of how to link error codes to messages you want users to see, there could be a CommonCryptor function that converts error codes to human readable string. If not, then you could write your own. I would recommend using a switch.

    NSString *MyCodeToLocalizedDescription(CCCryptorStatus cryptorStatus)
    {
        switch(cryptorStatus) {
        case kCCDecodeError: return @"This is the error message I want users to see";
        …
        default: return @"Oh noes, unknown error";
        }
    }
    

    At that point setting the error is:

    NSDictionary userInfo = @{
        NSLocalizedDescriptionKey : MyCodeToLocalizedDescription(result)
    };
    *error = [NSError errorWithDomain:kBridgeEncryptorErrorDomain
                                 code:result
                             userInfo:userInfo];