Ios Error Handling Strategies
Contents |
DevJolt Awards Channels▼ CloudMobileParallel.NETJVM LanguagesC/C++ToolsDesignTestingWeb DevJolt Awards Design Tweet Permalink Handling Errors in iOS and OS X with Cocoa By José R.C. Cruz, September 25, 2012 Cocoa provides two classes for smooth handling swift error handling of errors: NSError and NSResponder, which allow programs to dispatch do try catch swift an error object and respond to it from key points in the application. Only by knowing the
Do Catch Swift
underpinnings of each class is it possible to write truly user-friendly apps. Whatever the cause, product errors make an application unpleasant to use if they are not
Swift 2 Error Handling
handled properly. They can lead to a crash or freeze during normal use, and they can endanger user data. Users become frustrated and developers look incompetent. To guard against product errors, developers should make Cocoa projects error-tolerant. This means being able to encapsulate an error as it occurs, to dispatch it, and to respond to swift 2 try catch it properly. Cocoa provides us with the tools to accomplish this in the form of the NSError and NSResponder classes. In this article, I examine how to create an error object and how to dispatch it on the application's event loop. I will also explore how to respond to the error, as well as how to alter it, and finally, how to assign the right recovery routine to an error. To follow, you'll need a basic understanding of Objective-C. All featured code is applicable to both OS X and iOS projects, unless stated otherwise. The Error Object The NSError class (Figure 1) serves as the basis for an error object. It lets the error be identified and categorized. It can carry a collection of localized strings needed to describe the error. It can even invoke a recovery routine for the given error. Figure 1. NSError offers two ways to create an error object. One way is with the factory method errorWithDomain:code:userInfo:. Thi
Some of these errors will be outside of your control, such as running out of disk space or losing network connectivity. Some of these errors will be recoverable, such as invalid user input. And, while
Swift Error Type
all developers strive for perfection, the occasional programmer error may also occur.If you’re swift catch nserror coming from other platforms and languages, you may be used to working with exceptions for the majority of error handling. When swift try catch nserror you’re writing code with Objective-C, exceptions are used solely for programmer errors, like out-of-bounds array access or invalid method arguments. These are the problems that you should find and fix during testing before http://www.drdobbs.com/architecture-and-design/handling-errors-in-ios-and-os-x-with-coc/240007940 you ship your app.All other errors are represented by instances of the NSError class. This chapter gives a brief introduction to using NSError objects, including how to work with framework methods that may fail and return errors. For further information, see Error Handling Programming Guide.Use NSError for Most ErrorsErrors are an unavoidable part of any app’s lifecycle. If you need to request data from a remote web https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/ErrorHandling/ErrorHandling.html service, for example, there are a variety of potential problems that may arise, including:No network connectivityThe remote web service may be inaccessibleThe remote web service may not be able to serve the information you requestThe data you receive may not match what you were expectingSadly, it’s not possible to build contingency plans and solutions for every conceivable problem. Instead, you must plan for errors and know how to deal with them to give the best possible user experience.Some Delegate Methods Alert You to ErrorsIf you’re implementing a delegate object for use with a framework class that performs a certain task, like downloading information from a remote web service, you’ll typically find that you need to implement at least one error-related method. The NSURLConnectionDelegate protocol, for example, includes a connection:didFailWithError: method:- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;If an error occurs, this delegate method will be called to provide you with an NSError object to describe the problem. An NSError object contains a numeric error code, domain and description, as well as other relevant information packaged in a user info dictionary.Rather than making the requirement that every possible error have a unique numeric code, Cocoa and Cocoa Touch errors are divided into domains. If
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and http://stackoverflow.com/questions/1667994/best-practices-for-error-logging-and-or-reporting-for-iphone policies of this site About Us Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags http://mjtsai.com/blog/2014/07/13/swift-and-cocoa-error-handling/ Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes error handling a minute: Sign up Best Practices for Error Logging and/or reporting for iPhone up vote 27 down vote favorite 32 When I do web development, I use a custom made logger that catches fatal errors and appends a trace to a file and displays a message to the user. I can occasionally glance to see if the file changed, which means, ios error handling some user encountered an error and I can dig in to see what they encountered. I'd like something similar on the iphone, with some caveats: While developing, it should be trivial to reset the list of errors or turn off notification. While developing, the error messages should also show up in some obvious place, like on the screen on in the console Once deployed, errors should politely be sent to the mothership for analysis (for a bug fix in the next update) Turn on Trace/Info logging when trying to track down a problem during development Turn off console logging for 'Release' to speed up things for the user Should clean-up after itself so as to be a good citizen on the phone Some Related Links Using GSLog for instead of NSLog logging to a file on the iphone On the Mac, people say Apple System Logger and GTM Logger are the way to go objective-c logging best practices Jeff A's Blog entry on logging It seem like there would be a common toolkit to do this - how do you hand
to return an NSError back to your caller. This is very common with Cocoa. NSError is unwieldy, especially when you must consider that the output parameter could be NULL. The way I handle this in Objective-C is to use a macro to reduce the amount of error handling code that’s visible: NSError *e = nil; NSString *string = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&e]; MJT_REQUIRE(string, e, error); [string doSomething]; This leaves straight-line code, with no indentation, for the normal case. The macro, inspired by Apple’s AssertMacros.h, does nothing if its first parameter indicates success. Otherwise, it propagates the second parameter (the local error object) to the third parameter (the passed-in error pointer), but only if the latter isn’t NULL. It can also add some contextual information to error object, to track the source of the error. Lastly, it returns nil to indicate failure to the caller. (I also have MJT_BOOL_REQUIRE(), which returns NO instead of nil, and MJT_REQUIRE_PARAMETER(param, error), for when a parameter can’t be nil. This is sometimes preferable to raising an exception with NSParameterAssert(), and it is otherwise very verbose to construct an appropriate NSError to return.) Swift doesn’t have macros, so it’s not clear to me how this sort of pattern can be encapsulated. It looks like the code would be something like this: var e : NSError? let possibleString = NSString(contentsOfURL:url, encoding:NSUTF8StringEncoding, error:&e) if possibleString == nil { if error { error.memory = addErrorContext(e, context) } return nil } let string = possibleString as NSString string.doSomething() I don’t like the way this code looks. I could probably write a helper function to make it something like: var e : NSError? let possibleString = NSString(contentsOfURL:url, encoding:NSUTF8StringEncoding, error:&e) if failed(possibleString, e, error) { return nil } let string = possibleString as NSString string.doSomething() But I don’t see how to hide that if and return. And then there is the matter of having to create a second variable for the non-optional string if you don’t want to add ! after