Rejecting a the returned promise inside a then block - swift

Say I have two promises I want to combine with a when(resolved:). I want to reject the promise if there was a problem with the first promise, but resolve otherwise. Essentially, this is what I want to do:
func personAndPetPromise() -> Promise<(Person, Pet?)> {
let personPromise: Promise<Person> = ...
let petPromise: Promise<Pet> = ...
when(resolved: personPromise, petPromise).then { _ -> (Person, Pet?) in
if let error = personPromise.error {
return Promise(error: error) // syntax error
}
guard let person = personPromise.value else {
return Promise(error: myError) // syntax error
}
return (person, petPromise.value)
}
}
such that externally I can do something like this:
personAndPetPromise().then { person, pet in
doSomethingWith(person, pet)
}.catch { error in
showError(error)
}
The problem lies within the the then { _ in block in personAndPetPromise. There's no way that method can return both a Promise(error:) and a (Person, Pet?).
How else can I reject the block?

The problem is that there are two overloads of the then function:
public func then<U>(on q: DispatchQueue = .default, execute body: #escaping (T) throws -> U) -> Promise<U>
public func then<U>(on q: DispatchQueue = .default, execute body: #escaping (T) throws -> Promise<U>) -> Promise<U>
The first one's body returns a U and causes then to return Promise<U>.
The second one's body returns a Promise<U> and causes then to return Promise<U>.
Since in this case we want to return an error or a valid response, we're forced to use the second overload.
Here's a working version. The main difference is I changed it from -> (Person, Pet?) to -> Promise<(Person, Pet?)>:
func personAndPetPromise() -> Promise<(Person, Pet?)> {
let personPromise: Promise<Person> = ...
let petPromise: Promise<Pet> = ...
when(resolved: personPromise, petPromise).then { _ -> Promise<(Person, Pet?)> in
if let error = personPromise.error {
return Promise(error: error)
}
guard let person = personPromise.value else {
return Promise(error: myError)
}
return Promise(value: (person, petPromise.value))
}
}
Another way to do the same thing is by throwing the error rather than attempting to return it:
func personAndPetPromise() -> Promise<(Person, Pet?)> {
let personPromise: Promise<Person> = ...
let petPromise: Promise<Pet> = ...
when(resolved: personPromise, petPromise).then { _ -> (Person, Pet?) in
if let error = personPromise.error {
throw error
}
guard let person = personPromise.value else {
throw myError
}
return (person, petPromise.value)
}
}

Related

Cannot map error after flatMap usage (Never result type)

I have RestManager class which is used for fetching data from Internet and is returning AnyPublisher
class RestManager {
func fetchData<T: Decodable>(url: URL) -> AnyPublisher<T, ErrorType> {
URLSession
.shared
.dataTaskPublisher(for: url)
.tryMap({ data, _ in
let value = try JSONDecoder().decode(T.self, from: data)
if let array = value as? Array<Any>, array.isEmpty {
throw ErrorType.empty
}
return value
})
.mapError { error -> ErrorType in
switch error {
case is ErrorType:
return ErrorType.empty
case let urlError as URLError:
switch urlError.code {
case .notConnectedToInternet, .networkConnectionLost, .timedOut:
return .noInternetConnection
case .cannotDecodeRawData, .cannotDecodeContentData:
return .empty
default:
return .general
}
default:
return .general
}
}
.eraseToAnyPublisher()
}
}
Repository has two functions (getWorldwideData and getCountryData returning AnyPublisher<(WorldwideResponse item or CountryResponse item), ErrorType>)
In viewModel, I made these functions.
private func getData() {
$useCaseSelection
.flatMap { value -> AnyPublisher<Covid19StatisticsDomainItem, ErrorType> in
self.loader = true
self.error = nil
switch value {
case let .country(name):
return self.countryPipeline(name: name)
case .worldwide:
return self.worldwidePipeline()
}
}
.mapError { error in
self.error = error
}
.assign(to: &$homeScreenDomainItem)
}
private func worldwidePipeline() -> AnyPublisher<Covid19StatisticsDomainItem, ErrorType> {
repository
.getWorldwideData()
.map { response -> Covid19StatisticsDomainItem in
self.error = nil
self.loader = false
return Covid19StatisticsDomainItem(worldwideResponseItem: response)
}
.eraseToAnyPublisher()
}
private func countryPipeline(name: String) -> AnyPublisher<Covid19StatisticsDomainItem, ErrorType> {
repository
.getCountryData(for: name)
.map { response -> Covid19StatisticsDomainItem in
self.error = nil
self.loader = false
return Covid19StatisticsDomainItem(countryDayOneStatsResponse: response)
}
.eraseToAnyPublisher()
}
I wanted to make clean code, so I split code into two separate function based on useCaseSelection.
useCaseSelection is enum with two types.
error is ErrorType? value wrapped with #Published, in which I want to save error type if there is any error.
homeScreenDomainItem is Covid19StatisticsDomainItem instance wrapped with #Published.
Problem is in getData function where in MapError pipeline I am getting:
Cannot convert value of type () to closure result type Never
I tried to use setFailureType(to: ErrorType.self) but that is not helping.

How to return a failure inside .map function in a Result

I have a method execute that calls an external API with a callback that receives Result<Data?,Error>. How can I map that optional success to an unwrapped result or an Error?
func execute(then handle: #escaping (Result<Data, Error>) -> Void) {
externalAPI.retrieveData { result in
let mappedResult = result
.map {
guard let data = $0 else {
throw NSError(domain: "", code: 0, description: "error")
}
return data
}
handle(mappedResult)
}
}
This code fails with Invalid conversion from throwing function of type '(Optional<Data>) throws -> _' to non-throwing function type '(Data?) -> NewSuccess'
I was able to do this with a simple switch (below), but I was wondering if throwing a failure inside the .map is possible.
func execute(then handle: #escaping (Result<Data, Error>) -> Void) {
externalAPI.retrieveData { result in
switch result {
case .failure(let error):
handle(.failure(error))
case .success(let data):
guard let data = data else {
handle(.failure(NSError(domain: "", code: 0, description: "error")))
return
}
handle(.success(data))
}
}
}
You can convert between throws functions and functions that return Result<Success, Error> by using Result(catching:) and .get().
Here's your original map call:
.map {
guard let data = $0 else {
throw NSError(domain: "", code: 0, description: "error")
}
return data
}
Result.map takes a Result and a function that converts (Success) -> NewSuccess, and returns a Result<NewSuccess, Failure>.
Your map takes a Data (Success), and returns Result<Data, Error> (NewSuccess). So the final type, by plugging in NewSuccess is: Result<Result<Data, Error>, Error>. That's more layers than you want. You want to flatten that to just Result<Data, Error>, and that's where flatMap comes in.
Your answer shows that, but you can also pull this out into a more general-purpose tool. It only works when Failure == Error, because throws is untyped, so you can't limit it to some subset of errors. But that's what you're doing anyway. Here's tryMap:
extension Result where Failure == Error {
func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> Result<NewSuccess, Error> {
self.flatMap { value in
Result<NewSuccess, Error> { try transform(value) }
}
}
}
With that, you can rewrite this as:
func execute(then handle: #escaping (Result<Data, Error>) -> Void) {
externalAPI.retrieveData { result in
handle(result
.tryMap {
guard let data = $0 else {
throw NSError(domain: "", code: 0, description: "error")
}
return data
})
}
}
That said, I'd probably be tempted to write it this way:
func execute(then handle: #escaping (Result<Data, Error>) -> Void) {
externalAPI.retrieveData { result in
handle(result
.flatMap { maybeData in
maybeData.map(Result.success)
?? .failure(NSError(domain: "", code: 0, description: "error"))
})
}
}
Or if I wanted someone to be able to actually read it later:
func execute(then handle: #escaping (Result<Data, Error>) -> Void) {
externalAPI.retrieveData { result in
handle(result
.flatMap {
switch $0 {
case .some(let data): return .success(data)
case .none: return .failure(NSError(domain: "", code: 0, description: "error"))
}
}
)
}
}
The advantage of this switch over yours is that you don't have to unwrap and rewrap previous failures.
Apparently, this can be done using flatmap. So in my case:
func execute(then handle: #escaping (Result<Data, Error>) -> Void) {
externalAPI.retrieveData { result in
let mappedResult = result
.flatMap { data in
Result<Data, Error> {
guard let data = data else {
throw NSError(domain: "", code: 0, description: "error")
}
return data
}
}
handle(mappedResult)
}
}
It's a little confusing, but it is working for me.

RxSwift+Alamofire custom mapper error handling

RxSwift one more question about error handling:
I'm using Alamofire+RxAlamofire this way:
SessionManager.default.rx.responseJSON(.post, url, parameters:params)
example:
func login() -> Observable<Int> {
let urlString = ...
let params = ...
return SessionManager.default.rx.responseJSON(.post, url, parameters:params)
.rxJsonDefaultResponse()
.map({ (data) in
data["clientId"] as! Int
})
}
....
extension ObservableType where Element == (HTTPURLResponse, Any) {
func rxJsonDefaultResponse() -> Observable<Dictionary<String, Any>> {
return self.asObservable().map { data -> Dictionary<String, Any> in
if... //error chechings
throw NSError(domain: ..,
code: ...,
userInfo: ...)
}
...
return json
}
}
}
using:
loginBtn.rx.tap
.flatMap{ _ in
provider.login()
}.subscribe(onNext: { id in
...
}, onError: { (er) in
ErrorPresentationHelper.showErrorAlert(for: er)
})
.disposed(by: bag)
So if error occurred everything works as intended: error alert shows and 'loginBtn.rx.tap' disposed, but I need it to be still alive, what's my strategy here if I want to use onError block?
You can use materialize function in rxSwift. It will convert any Observable into an Observable of its events. So that you will be listening to Observable<Event<Int>> than Observable<Int>. Any error thrown from the flatmap would be captured as error event in your subscription block's onNext and can be handled there. And your subscription would still be alive. Sample code would be as follows.
button.rx.tap.flatMap { _ in
return Observable.just(0)
.flatMap { _ -> Observable<Int> in
provider.login()
}.materialize()
}.subscribe(onNext: { event in
switch event {
case .next:
if let value = event.element {
print(value) //You will be getting your value here
}
case .error:
if let error = event.error {
print(error.localizedDescription) //You will be getting your captured error here
}
case .completed:
print("Subscription completed")
}
}) {
print("Subscription disposed")
}.disposed(by: disposeBag)
Hope it helps. You can checkout the materialize extension here.

How to write a template function that handle do catch

I want to write a template function that handle do catch. It may look like this
func handleMethod(methodNeedToHandle) -> result: notSureType{
var result
do {
let response = try handleMethod
result = response
return result
} catch let error as someObjectError{
result = error
return result
}
}
Then you can use it like
let catchResult = handleMethod(method(x: something, y: something))
Thank you guys help me a lot, I get working code below
func handleDoTryCatch<T>(closure:() throws -> T) -> Any {
do {
let result = try closure()
return result
} catch let error {
return error
}
}
You could use a generic function that takes a closure and returns a tuple.
Something like:
func handle<T>(closure:() throws -> T) -> (T?, Error?) {
do {
let result = try closure()
return (result, nil)
} catch let error {
return (nil, error)
}
}
This will define a function that takes a closure that calls the method that can throw. It the returns a tuple with the expected return type and something that conforms to the Error protocol.
You would use it like this:
let result: (Void?, Error?) = handle { try someFunc() }
let result2: (Int?, Error?) = handle { try someOtherFunc(2) }
someFunc and someOtherFunc are just examples and their signatures would be:
func someFunc() throws {}
func someOtherFunc(_ param: Int) throws -> Int {}
This is the function I managed to come up with:
// Your error cases
enum Errors: Error {
case someErrorCase
}
// Function to test another function
func doTryCatch<T>(for function: () throws -> T) {
do {
let returnValue = try function()
print("Success! The return value is \(returnValue)")
} catch {
print("Error! The error reason was \"\(String(describing: error))\"")
}
}
// Function to test
func failingFunction() throws -> Int {
throw Errors.someErrorCase // <-- Comment this to not recieve an error (for testing)
return 5 // Will return 5 if the error is not thrown
// Failure: Error! The error reason was "someErrorCase"
// Success: Success! The return value is 5
}
// Perform the test
doTryCatch(for: failingFunction) // <-- Very easy to test, no closures to write!
Hope this helps with your debugging! :)
The closest I could get to what you probably want is the following:
(Swift Playground code:)
func handleMethod(_ f: #autoclosure () throws -> Void) -> Error? {
do {
try f()
} catch let err {
return err
}
return nil
}
enum HelloError: Error {
case tooShort
}
func hello(_ what: String) throws {
guard what.count > 0 else { throw HelloError.tooShort }
print ("Hello \(what)!")
}
// use like this:
// let err = handleMethod(try hello("World")) // err == nil
// let err = handleMethod(try hello("")) // err == HelloError.tooShort
//
print ("* hello(\"World\") -> \(String(describing: handleMethod(try hello("World"))))")
print ("* hello(\"\") -> \(String(describing: handleMethod(try hello(""))))")
This will produce the following output:
Hello World!
* hello("World") -> nil
* hello("") -> Optional(__lldb_expr_3.HelloError.tooShort)
Consider just using do/catch as George_E recommends. It's a good advice. But if you need this function, than this snipped hopefully gives you a starting point.

Invalid conversion of recover block, PromiseKit

This code
let promise: Promise<Supplier> = self.supplierController
.update(supplier: supplier)
let block: ((Error) throws -> Supplier) = { (error: Error) throws -> Supplier in
let supplier: Supplier = supplier
guard (error as NSError).code == 405 else {
throw error
}
return supplier
}
let newPromise =
promise
.recover(block)
.done { (_: Supplier) in
changeCompanyIdAndAppendMessage()
}
gives compile time error
invalid conversion from throwing function of type '(Error) throws ->
Supplier' to non-throwing function type '(Error) ->
Guarantee'
Why does it try to convert? It seems to me, it has to use this func:
public func recover(on: DispatchQueue? = default, policy:
PromiseKit.CatchPolicy = default, _ body: #escaping (Error) throws ->
U) -> PromiseKit.Promise where U : Thenable, Self.T == U.T
from PromiseKit
I added explicit types and divided promise into blocks to not miss something
You should return Promise to chain correctly, like this :
self.supplierController
.update(supplier: supplier)
.recover { error -> Promise<Supplier> in
let supplier: Supplier = supplier
guard (error as NSError).code == 405 else {
throw error
}
return .value(supplier)
}
.done { (_: Supplier) in
changeCompanyIdAndAppendMessage()
}
source: https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md