0

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?

Matthew Exon
  • 467
  • 4
  • 16

2 Answers2

1

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];
}
Juraj Antas
  • 3,059
  • 27
  • 37
  • Fair enough. A bit more of a faff then I was hoping for, but this ain't PHP ;-) I didn't know about mutableCopy, that helps a bit, thanks. – Matthew Exon Apr 23 '14 at 11:42
0

A good practice is to raise your own NSException, or preferably just pass an NSError, encapsulating the original one, which could be using userInfo.

In your case, you can't call setValue: on NSException, just simply because it doesn't handle it. Look at an NSException as read-only.`

More generally, exceptions should not be used as messages, prefer errors.

Vincent Guerci
  • 14,379
  • 4
  • 50
  • 56