Frage

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?

War es hilfreich?

Lösung

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];
}

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top