ios - Unified response/error handling in swift -
im wondering how tackle such problem:
i have application lets user log in username , password. application sends credentials api server , in response gets logged user data
in model defined user class
class user { var id: string var firstname: string? var lastname: string? var email: string var permissions: string? var birthday: string? var subscription: string? init(id: string, firstname: string?, lastname: string?, email: string, permissions: string?, birthday: string?, subscription: string?) { self.id = id self.firstname = firstname self.lastname = lastname self.email = email self.permissions = permissions self.birthday = birthday self.subscription = subscription }
then in class called apiconnector, have (using afnetworking):
func loginuser(mainaddress: string, additionaladdr: string, email: string, password: string, callback: (success: bool, data: user) -> void){ let fulladdress = mainaddress + additionaladdr var parameters = ["email":email, "password":password] manager.post( fulladdress, parameters: parameters, success: { (operation: afhttprequestoperation!,responseobject: anyobject!) in let json = json(data: operation.responsedata) //here have json user data callback(success: true, data: ???) }, failure: { (operation: afhttprequestoperation!,error: nserror!) in let json = json(data: operation.responsedata) //here have json error callback(success: false, data: ???) }) }
right u can see have callback returning user in data field. there problem when error occures , should returning errortype, not user.
i thinking how unify response create
enum result<t, e> { case ok(t) case error(e) }
and in ok case return user object. in case of error return errortype object - kinda cannot head around it.
could explain me how unified response type in case ?
(i placed question marks instead of type in code, cause thats question , have no solution atm)
i'd go optional , exchange success decorated nserror nice error messages. example this:
class user {} class serverresponseerror { var error: nserror var message: string { { switch(error.code) { case 500: return "server error" default: return "unknown error" } } } init(error: nserror) { self.error = error } } func loginuser(callback: (user: user?, error: serverresponseerror?) -> void){ // went wrong on server var error: nserror = nserror(domain: "", code: 500, userinfo: nil) callback(user: nil, error: serverresponseerror(error:error)) } loginuser { (user, error) -> void in print(error.message) }
you can decorate error object returned server , pass same way (with user nil). think it's bad practice return 200 , error object.
Comments
Post a Comment