Skip to content

Instantly share code, notes, and snippets.

@GeekAndDad
Created March 12, 2022 18:38
Show Gist options
  • Save GeekAndDad/98eea1aed2d10fc077ef4d1dfba60ca6 to your computer and use it in GitHub Desktop.
Save GeekAndDad/98eea1aed2d10fc077ef4d1dfba60ca6 to your computer and use it in GitHub Desktop.
Simple test around throwing close function and api design
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")
@GeekAndDad
Copy link
Author

GeekAndDad commented Mar 12, 2022

Output with boolean parameters as in gist (play with them to explore code):

doing test()

opened connection
throwing during doWork
throwing during close connection
test threw: fakeWork

done test()-ing


Doing betterTest

opened connection
throwing during doWork
throwing during close connection
Silencing error thrown by close after previous errors
betterTest threw: fakeWork

Done with betterTest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment