Skip to content

Instantly share code, notes, and snippets.

@rainbowcardiod
Last active June 8, 2022 12:42
Show Gist options
  • Save rainbowcardiod/7201eed3ee1f22a751af5737ec861035 to your computer and use it in GitHub Desktop.
Save rainbowcardiod/7201eed3ee1f22a751af5737ec861035 to your computer and use it in GitHub Desktop.
nicer cacth-log-error syntax for swift
/*
Many times one does a catch and just wants to log the error,
perhaps with an utility that in the log message includes the function name and the source code line.
With catchAndLog one can do the same but with a nicer and shorter syntax.
Example, before:
do {
... code ...
} catch {
functionToLogError("\(error)")
}
After:
catchAndLog {
... code ...
}
Note well: using "return" inside the catchAndLog block would not have the intended effect!
*/
var DEBUG = true
public func catchAndLog(message: String = "", file: String = #file, function: String = #function, line: Int = #line, closure: () throws -> Void) {
do {
try closure()
} catch {
logError(message + " \(error)", file: file, function: function, line: line)
}
}
public func log(_ message: String, file: String = #file, function: String = #function, line: Int = #line ) {
logFunc("INFO", message: message, file: file, function: function, line: line)
}
public func logError(_ message: String, file: String = #file, function: String = #function, line: Int = #line ) {
logFunc("ERROR", message: message, file: file, function: function, line: line)
}
public func logDebug(_ message: String, file: String = #file, function: String = #function, line: Int = #line ) {
DispatchQueue.main.async { // read in the main thread the DEBUG variable (and also set it the main thread)
if DEBUG {
logFunc("DEBUG", message: message, file: file, function: function, line: line)
}
}
}
public func logFunc(_ tag: String, message: String, file: String = #file, function: String = #function, line: Int = #line ) {
let message = "\(tag): \(debugCoordinates(file: file, function: function, line: line)) \(message)"
NSLog(message)
}
public func debugCoordinates(file: String = #file, function: String = #function, line: Int = #line) -> String {
let smallFunction: String
if let idx = function.firstIndex(of: "(") {
smallFunction = String(function[..<idx])
} else {
smallFunction = function
}
let smallFile: String
if let idx = file.lastIndex(of: "/") {
smallFile = String(file[file.index(after: idx)...])
} else {
smallFile = file
}
return "\(smallFile):\(smallFunction):\(line)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment