2016-03-08 52 views
1

我應該從函數拋出一個異常方便的功能它內部調用:從調用函數傳遞誤差達是雨燕2.1

public func save() throws -> Bool { 

      do { 

       return try self.save(self.filePath) 

      } catch { 
       // How to throw error from the function save(filePath:) ?? 
      } 

      return false 
     } 

public func save(filePath: String) throws -> Bool { 

do { 

      let jsonData = try NSJSONSerialization.dataWithJSONObject(self.jsoNObject, options: NSJSONWritingOptions.PrettyPrinted) 
      return jsonData.writeToFile(self.filePath, atomically: true) 
     }catch { 
      throw PersistedError.NSJSONSerializationError 
      return false 
     } 
} 

如何通過或拋出由save(filePath: String)save()拋出的錯誤功能?

回答

1

一種方法可能是catch特定的錯誤,然後就throw一遍:

public func save() throws -> Bool { 
    do { 
     return try save("foo") 
    } catch let error as NSError { 
     throw error 
    } 
} 

public func save(filePath: String) throws -> Bool { 
    do { 
     let jsonData = try NSJSONSerialization.dataWithJSONObject([:], options: NSJSONWritingOptions.PrettyPrinted) 
     return jsonData.writeToFile("foo", atomically: true) 
    } catch { 
     throw NSError(domain: "", code: 0, userInfo: [:]) 
    } 
} 

或者,如果你不需要任何額外的錯誤處理更簡單 - 這將只是簡單地提出了錯誤:

public func save() throws -> Bool { 
    return try save("foo") 
} 

public func save(filePath: String) throws -> Bool { 
    do { 
     let jsonData = try NSJSONSerialization.dataWithJSONObject([:], options: NSJSONWritingOptions.PrettyPrinted) 
     return jsonData.writeToFile("foo", atomically: true) 
    } catch { 
     throw NSError(domain: "", code: 0, userInfo: [:]) 
    } 
}