Last active
April 27, 2016 12:14
-
-
Save erica/6b06d78849ad47ce8bff to your computer and use it in GitHub Desktop.
This file contains 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
/// consists of file path, line number, error tuple | |
public typealias CommonErrorHandlerType = (String, Int, ErrorType) -> Void | |
/// Default error handler prints context and error | |
public let defaultCommonErrorHandler: CommonErrorHandlerType = { | |
filePath, lineNumber, error in | |
let trimmedFileName: String = (filePath as NSString).lastPathComponent | |
print("Error \(trimmedFileName):\(lineNumber) \(error)") | |
} | |
/// Replacement for `try?` that introduces an error handler | |
/// The default error handler prints an error before returning nil | |
public func attempt<T>( | |
file fileName: String = __FILE__, | |
line lineNumber: Int = __LINE__, | |
crashOnError: Bool = false, | |
errorHandler: CommonErrorHandlerType = defaultCommonErrorHandler, | |
// Thanks, http://twitter.com/Kametrixom/status/709809975447707648 | |
@noescape closure: () throws -> T) -> T? { | |
do { | |
// Return executes only if closure succeeds, returning T | |
return try closure() | |
} catch { | |
// Emulate try! by crashing | |
if crashOnError { | |
print("Fatal error \(fileName):\(lineNumber): \(error)") | |
fatalError() | |
} | |
// Execute error handler and return nil | |
errorHandler(fileName, lineNumber, error) | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment