Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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()

This comment has been minimized.

Copy link

BenziAhamed commented Feb 24, 2017

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


This comment has been minimized.

Copy link

marcosgriselli commented Aug 11, 2017

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 can’t perform that action at this time.