Created
March 12, 2022 18:38
-
-
Save GeekAndDad/98eea1aed2d10fc077ef4d1dfba60ca6 to your computer and use it in GitHub Desktop.
Simple test around throwing close function and api design
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum ConnectionError: Error { | |
case fakeWork | |
case close | |
case connect | |
} | |
struct Connection { | |
func close(fail: Bool = false) throws { | |
if fail { | |
print("throwing during close connection ") | |
throw ConnectionError.close | |
} | |
print("closing connection") | |
} | |
static func connect(fail: Bool = false) throws -> Connection { | |
if fail { | |
print("throwing during open connection") | |
throw ConnectionError.connect | |
} | |
print("opened connection") | |
return Connection() | |
} | |
} | |
func doWork(fail: Bool) throws { | |
if fail { | |
print("throwing during doWork") | |
throw ConnectionError.fakeWork | |
} | |
print("work done successfully") | |
} | |
func test() throws { | |
let connection = try Connection.connect(fail: false) | |
defer { | |
do { | |
try connection.close(fail: true) | |
} catch { | |
// Can't throw from a defer | |
// if doWork succeeds but close fails then we'd like to throw the close error... | |
// otherwise close shouldn't be a throwing function. | |
} | |
} | |
try doWork(fail: true) | |
} | |
// Have to write it like this, unless there's a better way? | |
// play with booleans passed to connect(), doWork(), and close() (two spots) | |
// to explore behavior. | |
func betterTest() throws { | |
let connection = try Connection.connect(fail: false) | |
do { | |
try doWork(fail: true) | |
try connection.close(fail: false) | |
print("success!") | |
} | |
catch ConnectionError.close { | |
throw ConnectionError.close | |
} | |
catch { | |
do { | |
try connection.close(fail: true) | |
} catch { | |
print("Silencing error thrown by close after previous errors") | |
} | |
throw error | |
} | |
} | |
// testing: | |
print("doing test()\n") | |
do { | |
try test() | |
print("success!") | |
} catch { | |
print( "test threw: \(error)") | |
} | |
print("\ndone test()-ing\n\n---\n\n") | |
print("Doing betterTest\n") | |
do { | |
try betterTest() | |
} catch { | |
print("betterTest threw: \(error)") | |
} | |
print("\nDone with betterTest\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output with boolean parameters as in gist (play with them to explore code):