try catch - In Swift 2, how can I return JSON parsing errors to the completion block? -


i create function in swift 2 gets data url , returns json object using nsurlsession. @ first, seemed pretty straight forward. wrote following:

func getjson(url:nsurl, completewith: (anyobject?,nsurlresponse?,nserror?)->void) -> nsurlsessiontask? {      let session = nsurlsession.sharedsession()     let task = session.datataskwithurl(url) {         (data:nsdata?, response:nsurlresponse?, error:nserror?) -> void in          if error != nil {             completewith(nil, response, error)         }          if let data = data {              {                 let object:anyobject? = try nsjsonserialization.jsonobjectwithdata(data, options: .allowfragments)             } catch let caught nserror {                 completewith(nil, response, caught)             }              completewith(object, response, nil)          } else {             completewith(nil, response, error)         }     }      return task } 

however, doesn't compile because completion block doesn't declare "throws". exact error cannot invoke 'datataskwithurl' argument list of type '(nsurl, (nsdata?, nsurlresponse?, nserror?) throws -> void)'. though i'm catching errors in do/catch statement, swift still wants propagate nserror chain. way can see around use try!, this:

if let data = data {      let object:anyobject? = try! nsjsonserialization.jsonobjectwithdata(data, options: .allowfragments)     completewith(object, response, nil)  } else {     completewith(nil, response, error) } 

now compiles fine, i've lost nserror that's thrown nsjsonserialization.jsonobjectwithdata.

is there can capture nserror potentially thrown nsjsonserialization.jsonobjectwithdata , propagate completion block without modifying completion block's signature?

i think, catch not exhaustive, need this:

do {   let object:anyobject? = try nsjsonserialization.jsonobjectwithdata(data, options: .allowfragments)   completewith(object, response, nil) } catch let caught nserror {   completewith(nil, response, caught) } catch {   // else happened.   // insert domain, code, etc. when constructing error.   let error: nserror = nserror(domain: "<your domain>", code: 1, userinfo: nil)   completewith(nil, nil, error) } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -