Skip to content

Instantly share code, notes, and snippets.

@erica
Last active April 27, 2016 12:14
Show Gist options
  • Save erica/6b06d78849ad47ce8bff to your computer and use it in GitHub Desktop.
Save erica/6b06d78849ad47ce8bff to your computer and use it in GitHub Desktop.
/// 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