Last active
December 21, 2019 14:43
-
-
Save JohnSundell/93c3ad78d00c47149ba3f8cde127b19e to your computer and use it in GitHub Desktop.
A function that enables you to easily wrap throwing APIs, to provide a custom error
This file contains hidden or 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
/** | |
* Perform a throwing expression, and throw a custom error in case the expression threw | |
* | |
* - parameter expression: The expression to execute | |
* - parameter error: The custom error to throw instead of the expression's error | |
* - throws: The given error | |
* - returns: The return value of the given expression | |
*/ | |
func perform<T>(_ expression: @autoclosure () throws -> T, orThrow errorExpression: @autoclosure () -> Error) throws -> T { | |
do { | |
return try expression() | |
} catch { | |
throw errorExpression() | |
} | |
} |
I had to go with
catch _ {
throw error
}
as catch
was using the error thrown on try
rather than the error passed in the function
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should probably also mark the error parameter as an autoclosure, letting it be created only when an error happens.