I have this universal error handler for my HomeKit app (currently in development). It grew out of wanting a single place to write error messages, show alerts, etc. I wanted a short, simple way to call it from anywhere that may generate an error.
Here's the class:
import UIKit import HomeKit class ESErrorHandler : NSObject { class func handleError(error: NSError) -> Bool { NSLog("Handling error \(error) in centralized handler") let code = HMErrorCode(rawValue: error.code) switch code! { case HMErrorCode.FireDateInPast: showAlertWithTitle("Invalid date", body: "Date must be in the future") case HMErrorCode.AccessDenied: showAlertWithTitle("Access Denied", body: "You don't have permission to access the specified item") ... // A bunch more cases default: NSLog("Couldn't handle error with code \(error.code)") showAlertWithTitle("Error", body: "Couldn't successfully complete action") return false } return true } class func showAlertWithTitle(title: NSString, body: NSString) { dispatch_async(dispatch_get_main_queue()) { let alert = UIAlertView(title: title, message: body, delegate: nil, cancelButtonTitle: "OK") alert.show() } } } I call it from other code like this:
homeManager.addHomeWithName(currentHouseName) {(home: HMHome!, error: NSError!) in if error != nil { ESErrorHandler.handleError(error) self.title = "Add Home" } else { ... //Stuff worked, do other stuff } } My concerns:
- Something feels wrong about putting using a class method for
showAlertWithTitle:body: - I don't really like having using
switch code!, it seems clumsy like I'm missing something in unwrapping