Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add version of log(errorIfThrows:) which doesn't require a returned value #26

Open
KyNorthstar opened this issue Jun 8, 2023 · 0 comments

Comments

@KyNorthstar
Copy link
Contributor

log(errorIfThrows:backup:) is very useful for both ensuring that some value is used even if it isn't ideal, and also logging why a backup value needed to be used. However, it would also be very useful as a standalone log line for functions which don't return anything, like this:

log(errorIfThrows: try reloadCaches())

/// Calls the given function and, if it throws an error, logs that error (and the location where you called this
/// function) at `error` severity to the given channels, and the given backup function is called and its value is
/// returned. If the given function does not throw an error, then its result is returned and the backup function is not
/// called.
///
/// - Parameters:
/// - dangerousCall: A function which might throw an error
/// - channels: _optional_ - The channels to which to log the given item
///
/// - Returns: The return value of either `dangerousCall` if it doesn't throw an error, or of `backup` if it does
@inlinable
public func log<Return>(errorIfThrows dangerousCall: @autoclosure () throws -> Return,
backup: @autoclosure () -> Return,
to channels: [LogChannel] = LogManager.defaultChannels,
file: String = #file, function: String = #function, line: UInt = #line)
-> Return {
do {
return try dangerousCall()
}
catch {
log(error: error,
file: file, function: function, line: line,
to: channels)
return backup()
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant