An NSError error

I was originally going to remind people to check their error handling code is doing the right thing (I recently found some problems in our iMedia framework of this nature), but Big Nerd Ranch saved me the effort. So instead you got “Passing errors across threads using blocks”. Hey, two articles for the price of one. Awesome!


Following Simon Wolf's recent post, and Sam Deane's followup, I figured it was time I posted a real-world example of how shabby error checking could bite someone:

This is some of a routine from iMedia. It scans through a directory to see if there's any subfolders, to determine whether a disclosure triangle should appear. Thus there are three answers: "yes, it has subfolders", "nope, no subfolders here", and "not sure, I hit some errors", represented as @YES, @NO and nil. If nil is returned, callers can consult the error to see what upset the search.

What's interesting to note is that if testing a particular URL fails, but then the very next one turns out to be a folder, this routine will return @YES with the error pointer most likely filled in to the prior error. It's possible that -getResourceValue:… clears out the error pointer, but it's not obliged to. The routine itself also plays by the error handling rules.

So a dumb client of this method that checked the error pointer first, rather than the return value would think the method had failed when it hadn't. Even worse this would be a pretty rare occurrence, so the mistake likely wouldn't be spotted by the developer.

Long and short of it: play by the error handling rules. Always.

(OK, before you start complaining at me that you could just pass NULL to the -getResourceValue: calls, the point still stands. The method is totally entitled to do this. Callers should still behave appropriately. And in the full code this example is taken from, the error handed back from those calls does get used a little as well)

© Mike Abdullah 2007-2015