2

我有一个使用 CommonCryptor 加密和解密的包装器。有时解密过程会失败,在这种情况下,我会填写如下错误:

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

    return nil;
}

然后我记录这样的错误:

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

但是,这最终会生成如下字符串:

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.)

其中 -4304 可能是 CommonCryptor.h 中的任何错误代码(-4300 到-4305)。有没有一种将错误代码映射到其字符串值的好方法,或者我是否需要一个switch手动调整字符串的语句?如果我必须依赖 a switch,最佳做法是将其放在记录问题或生成错误的位置吗?

4

1 回答 1

2

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];
于 2013-01-09T15:45:58.727 回答