Creating an NSError in each catch block can lead to a large number of copies and ErrorType to convert custom ErrorType to NSError . I distracted him like @powertoold .
protocol CustomErrorConvertible { func userInfo() -> Dictionary<String,String>? func errorDomain() -> String func errorCode() -> Int }
This extension may contain code common to LifeError that we already have, and other custom error types that we can create.
extension CustomErrorConvertible { func error() -> NSError { return NSError(domain: self.errorDomain(), code: self.errorCode(), userInfo: self.userInfo()) } }
Disconnect to implementation!
enum LifeError: ErrorType, CustomErrorConvertible { case BeBorn case LostJob(job: String) case GetCaughtByPolice(police: String) func errorDomain() -> String { return "LifeErrorDomain" } func userInfo() -> Dictionary<String,String>? { var userInfo:Dictionary<String,String>? if let errorString = errorDescription() { userInfo = [NSLocalizedDescriptionKey: errorString] } return userInfo } func errorDescription() -> String? { var errorString:String? switch self { case .LostJob(let job): errorString = "fired as " + job case .GetCaughtByPolice(let cops): errorString = "arrested by " + cops default: break; } return errorString } func errorCode() -> Int { switch self { case .BeBorn: return 1 case .LostJob(_): return -9000 case .GetCaughtByPolice(_): return 50 } } }
And here is how to use it.
func lifeErrorThrow() throws { throw LifeError.LostJob(job: "L33tHax0r") } do { try lifeErrorThrow() } catch LifeError.BeBorn { print("vala morgulis") } catch let myerr as LifeError { let error = myerr.error() print(error) }
Can you easily move certain functions like func userInfo() -> Dictionary<String,String>? , from LifeError to extension CustomErrorConvertible or another extension.
Instead of hard coding, error codes may be preferred, for example, the above enumerations.
enum LifeError:Int { case Born case LostJob }
orkoden Oct 23 '15 at 17:10 2015-10-23 17:10
source share