Lukasz
Lukasz

Reputation: 19916

Passing errors up from the called function is Swift 2.1

I have a convenience function which should throw an error from the function it calls internally:

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
        }
}

How to pass or throw the error thrown by save(filePath: String) in the save() function?

Upvotes: 1

Views: 178

Answers (1)

Steffen D. Sommer
Steffen D. Sommer

Reputation: 2926

One approach could be to catch the specific error and then just throw it again:

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: [:])
    }
}

Or even simpler if you don't need any extra error handling - this will simply just forward the error:

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: [:])
    }
}

Upvotes: 1

Related Questions