Skip to content

Instantly share code, notes, and snippets.

@erica
Last active August 28, 2018 10:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save erica/af9fdef1ae2b9b9019d9 to your computer and use it in GitHub Desktop.
Save erica/af9fdef1ae2b9b9019d9 to your computer and use it in GitHub Desktop.
import Foundation
// Generic Error
public struct Error: ErrorType {let reason: String}
/**
Printing version of try? Call either with standard or autoclosure approach
```
let contents = attempt{try NSFileManager.defaultManager().contentsOfDirectoryAtPath(fakePath)}
let contents = attempt{try NSFileManager.defaultManager().contentsOfDirectoryAtPath(XCPlaygroundSharedDataDirectoryURL.path!)}
```
- Returns: Optional that is nil when the called closure throws
*/
public func attempt<T>(source source: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, closure: () throws -> T) -> Optional<T>{
do {
return try closure()
} catch {
let fileName = (file as NSString).lastPathComponent
let report = "Error \(fileName):\(source):\(line):\n \(error)"
print(report)
return nil
}
}
/**
A printing alternative to try? that returns Boolean value
```
let success = attemptFailable{try "Test".writeToFile(fakePath, atomically: true, encoding: NSUTF8StringEncoding)}
```
- Returns: Boolean value, false if the called closure throws an error, true otherwise
*/
public func attemptFailable(source source: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, closure: () throws -> Void) -> Bool {
do {
try closure()
return true
} catch {
let fileName = (file as NSString).lastPathComponent
let report = "Error \(fileName):\(source):\(line):\n \(error)"
print(report)
return false
}
}
/**
Slightly more informative version of try!. When shouldCrash is set to false,
execution will continue without a fatal error even if an error is thrown
```
doOrDie(shouldCrash: false, closure: {try "Test".writeToFile(fakePath, atomically: true, encoding: NSUTF8StringEncoding)})
// or
doOrDie(shouldCrash:false){try NSFileManager.defaultManager().removeItemAtURL(fakeURL)}
// or
doOrDie{try "Test".writeToFile(fakePath, atomically: true, encoding: NSUTF8StringEncoding)}
```
*/
public func doOrDie(source: String = __FUNCTION__,
file: String = __FILE__, line: Int = __LINE__, shouldCrash: Bool = true, closure: () throws -> Void) {
let success = attemptFailable(source: source, file: file, line: line, closure: closure)
if shouldCrash && !success {fatalError("Goodbye cruel world")}
}
@onmyway133
Copy link

It would be great if we convert this try/catch into Result<T, ErrorType>

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