I'm trying to write a global exception handling routine for my app. The idea is it will temporarily store the exception in memory and eventually report it to the server, rather than bothering the user.
I want to gather as much information as possible, so it seems like the userInfo field in the exception is the place to store it. Then I can simply rethrow the exception or, as in the below case, report it to the global exception handler directly and move on.
@catch (NSException *e) {
NSLog(@"Got exception parsing XML stack %@", stack);
[e setValue:stack forKey:@"stack"];
[__zmsGlobals exception:e context:@"Parsing data"];
[self cleanupAfterScan];
[self report:[NSError errorWithDomain:@"zaomengshe.com" code:104 userInfo:e.userInfo] selector:failureSelector];
}
This was just a guess as to how to set a value in the userInfo field. NSException seems to have a setValue method, but it doesn't work. It throws with "this class is not key value coding-compliant for the key stack."
So what's the best way to do this? Do I have to build a new NSException from scratch?
Yes, you need to create new NSException object, copy/add parts you want to have there and call raise again.
@catch (NSException* exception)
{
NSMutableDictionary* d = [[exception userInfo] mutableCopy];
[d setObject:@"new info" forKey:@"newKey"];
NSException * e = [NSException exceptionWithName:[exception name] reason:[exception reason] userInfo:d];
[e raise];
}