Skip to content

Instantly share code, notes, and snippets.

@erica erica/error.swift
Last active Aug 28, 2018

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Nov 26, 2015

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
You can’t perform that action at this time.