I am building a app with many different parts which access remote api calls (both my own, and others). There are many errors that might happen, and to exacerbate the problem, different libraries handle these errors differently.
Essentially, i would like to use the same error handling blocks for all these remote calls.
This is how i would do it with Ruby, but i am not that sure how to manipulate objective c in the same manner
//universal function to handle standard remote errors across errors
def universal_handling
begin
yield
rescue Exception => e
// handle different exceptions accordingly
// allow crash if unexpected exception
end
end
//how i would use the above block
universal_handling{ //any of my remote call here }
So, i have 2 questions (sample code very much appreciated)
- How would I write the equivalent code in Objective-C? It is critical that I can use the same handling block throughout the app
- In iOS dev, is this good practice?
Thanks for any help rendered! Error handling can be a major pain in the ass, so i do want to get this right early on =)
Notes:
- Blocks are perfectly fine. I am not intending to support < 4.2 versions.
- I read most of the articles out there, but none answers how you can use blocks to write “wrappers” for a specific set of calls.
You can do something very similar with blocks:
However, it’s very important to realize that the Cocoa (and CocoaTouch) libraries are not exception-safe. Throwing an exception through Cocoa frameworks will lead to all sorts of problems as the frameworks will not properly handle or clean up from the exceptions, leaving your application in a possibly inconsistent state. The correct Cocoa-style is to use
NSErrorand return flags to indicate error conditions. This is neither better nor worse than using exceptions, just a different philosophy.To do something similar to your
universal_handlingwithNSErroris not quite so straight forward because it will require that anything you call comply with theNSErrorpattern. That said:would wrap any method that takes just an
NSError**and returns aBOOLto indicate the presence of an error. Obviously the utility of this wrapper is limited as you’ll have to wrap any interesting method in an other block to handle any other parameters. Of course, since it’s theNSError**pattern, you can always just handle the errors when/where you want and passNULLas theNSError**parameter where you don’t care (ignoring the return value).One final note: if you are using libraries that may throw exceptions, you must catch those exceptions within the scope of the library call and handle them. Do not let the exceptions propagate as they might then propagate through Cocoa framework code. Thus, the utility of the
universal_handlingblock you propose is limited.