传输错误信息的版本稍好一些。
@implementation ObjCExceptionHandler
+ (BOOL)tryExecute:(nonnull void(NS_NOESCAPE^)(void))tryBlock error:(__autoreleasing NSError * _Nullable * _Nullable)error {
@try {
tryBlock();
return YES;
}
@catch (NSException *exception) {
NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] init];
if (exception.userInfo != NULL) {
userInfo = [[NSMutableDictionary alloc] initWithDictionary:exception.userInfo];
}
if (exception.reason != nil) {
if (![userInfo.allKeys containsObject:NSLocalizedFailureReasonErrorKey]) {
[userInfo setObject:exception.reason forKey:NSLocalizedFailureReasonErrorKey];
}
}
*error = [[NSError alloc] initWithDomain:exception.name code:0 userInfo:userInfo];
return NO;
}
}
@end
用法示例:
let c = NSColor(calibratedWhite: 0.5, alpha: 1)
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
do {
try ObjC.perform {
c.getRed(&r, green: &g, blue: &b, alpha: &a)
}
} catch {
print(error)
}
之前:
Error Domain=NSInvalidArgumentException Code=0 "(null)"
后:
Error Domain=NSInvalidArgumentException Code=0
"*** -getRed:green:blue:alpha: not valid for the NSColor NSCalibratedWhiteColorSpace 0.5 1; need to first convert colorspace."
UserInfo={NSLocalizedFailureReason=*** -getRed:green:blue:alpha: not valid for the NSColor NSCalibratedWhiteColorSpace 0.5 1; need to first convert colorspace.}