Thomvis / BrightFutures

Write great asynchronous code in Swift using futures and promises
MIT License
1.9k stars 184 forks source link

How to Log All Failed Promises? #147

Closed golfguy0082 closed 8 years ago

golfguy0082 commented 8 years ago

Hello, I'm trying to figure out the best approach for automatically logging all failed promises. When using methods that return a future, it is very easy to forget (or be lazy) and not handle error conditions. I'd like to provide some default logging to help diagnose issues that fall into this bucket. Do you have any suggestions of a way to inject a hook that would handle this logging?

darrenclark commented 8 years ago

It's not automatic unfortunately, but I have used something along the lines of this:

func logErrors<T, E>(f: Future<T, E>, file: String = #file, line: UInt = #line) -> Future<T, E> {
    return f.onFailure { error in
        print("Future failed: \(error), in '\(file)', line: \(line)")
    }
}

Usage:

func someFunctionReturningAFuture() -> Future<Int, NSError> { ... }

logErrors(someFunctionReturningAFuture())
    .onSuccess { value in
        print("Received value: \(value)")
    }

It'll print the error & provide the file & line number where logErrors was called.

Thomvis commented 8 years ago

There's no built in way to do this, but @darrenclark's solution should work. Other solutions might be creating a wrapper type (that also conforms to AsyncType) or create a function in an extension of AsyncType called logOnFailure() or something.