Sunday, January 7, 2007 [Tweets] [Favorites]

NSXReturnThrowError

Jonathan “Wolf” Rentzsch has posted some interesting Cocoa error-wrapping macros. I’ve long used some macros to generate and raise NSExceptions that have the name, reason, and userInfo set based on the error code, a format, and the location in the source file. Rentzsch’s macros go beyond this to stuff the relevant information into a more modern NSError object, with the error domain cleverly deduced from the function’s return type using @encode and typeof. The NSXThrowError macro will also raise an NSException that has the NSError stuffed into its userInfo. Lastly, the actual Objective-C expression that generated the error code is saved as a string in the NSError.

Putting on my code critiquing hat, I don’t like that NSXThrowError introduces an exception name beginning with the reserved NS prefix or that the function-like macros implicitly assign to an error variable in the local scope. Also, they should probably be do-while protected.

3 Comments

Thanks for the write-up! I'm glad you appreciated the @encode/typeof trickery.

Ooo, you're right about naming the NSException "NSError". Probably should go with NSXError or some such.

I agree implicit-assigning-to-error isn't great, but I think the tradeoff of always having to put "error" in the macro param list is worse.

Oh yeah, they should be do-while protected. I tend to forget that. I don't get burned because I run religious about always using braces with my if-style statements. The fix is in svn trunk, scheduled for 1.0.

Yeah, I agree that it's a tradeoff. It might be nice to have a version that takes a name and define NSXReturnError in terms of that. I think part of the reason it bugs me is that I tend to follow the frameworks and use "error" as the name of the method's output parameter.

Also, incidentally, when I first saw "Return" in the name I thought it meant "return from the calling function" or something, since that's what the "Throw" variant does. Maybe "Store" would be clearer.

The forerunner to these macros had an "NSXSetError" macro, which I thought was OK at the time. Now going back and looking at the code, I dislike it intensely. Strangely, I'm not sure why.

While writing this new version I had "NSXMakeError" hanging around, doing pretty much what you want. However I cut it thinking nobody would care. I put it back in :-)

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment