views:

1202

answers:

3

What's the best way to log an NSError?

- (void)epicFail:(Lol *)aLol withError:(NSError *)error
{
    NSLog(@"Error: %@", error);
}

Gives me a null message

Thanks.

+8  A: 
NSLog(@"Error: %@", error);

Gives me a null message

Then error is nil, not an NSError instance.

Peter Hosey
Thanks, this helps a lot. I thought I was doing something wrong. What is the best way to log an error then?
nevan
Doesn't he need to dereference the `NSError**` as well?
fbrereto
The original question didn't have two asterisks. Abizern added the second asterisk; I've rolled back his edit, because I don't think it makes sense for the actual question. If it were a double-asterisk argument, it would generally (esp. for an NSError) be an *output* argument, so the method should not attempt to retrieve an object through that pointer.
Peter Hosey
nevan: NSLog, exactly the way you're doing it. You need to have an error to log before you can log an error; your problem (insofar as it's a problem) is that you don't have an error.
Peter Hosey
+4  A: 

Looking at the NSError documentation tells me that you'll need to do something like:

NSLog(@"%@",[error localizedDescription]);

This should then give you human readable output

James Raybould
Well, he needs to have an error to get a description of, first. And the error's `description` will (currently) at least contain the error's domain and code, which may be more useful in a console log message.
Peter Hosey
Thanks, I'd seen this function, but I didn't understand why the log was giving me (null).
nevan
+1  A: 

Here's a rough method I use to log errors while developing; (Not for Cocoa-touch)

// Execute the fetch request put the results into array
NSError *error = nil;
NSArray *resultArray = [moc executeFetchRequest:request error:&error];
if (resultArray == nil)
{
    // Diagnostic error handling
    NSAlert *anAlert = [NSAlert alertWithError:error];
    [anAlert runModal];
}

NSAlert takes care of displaying the error.

Abizern
Of course, that's only useful on the Mac. UIKit doesn't have NSAlert.
Peter Hosey
Yeah! I didn't read the tags. Thanks for the rollback on the edit. I still think this answer is useful to leave up for others, as long as they take note it's only for the desktop.
Abizern