Skip to content

Instantly share code, notes, and snippets.

@JohnSundell
Last active December 21, 2019 14:43
Show Gist options
  • Star 35 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JohnSundell/93c3ad78d00c47149ba3f8cde127b19e to your computer and use it in GitHub Desktop.
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
/**
* 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()
}
}
@BenziAhamed
Copy link

You should probably also mark the error parameter as an autoclosure, letting it be created only when an error happens.

@marcosgriselli
Copy link

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