RxMoya Network and Service Error handling in the same function

1.9k Views Asked by At

I am trying to implement a function that handles Network & API errors, my problem is how to emit an observable again after filterSuccessfulStatusCodes(). The main issue I have is that I am not sure if this approach is correct, after the first subscribe.

The current error I have in this code is : Extra argument 'onError' in call

func Request<T: Decodable>(_ request: APIManager) -> 
Observable<Result<T>> {
    provider.rx
        .request(request)
        .subscribe(onSuccess: { (response) in
            try response.filterSuccessfulStatusCodes()
            return Observable.just(response)
                .subscribe { event in
                    switch event {
                    case .success:
                        .map(RequestResponse<T>.self)
                            .map { $0.result! }
                            .asObservable()
                            .map(Result.success)
                            .catchError { error in
                                return .just(.error(withMessage: "Error \(error)"))
                        }
                    case .error:
                        print("error")
                    }
            }

        }, onError: { (error) in
            print("network request error")

        }, onCompleted: {
            print("network request on completed")
        }).disposed(by: disposeBag)
}

 struct RequestResponse<T: Decodable> {
    let statusCode: Int
    let statusMessage: String
    let success: Bool
    let result: T?
    let errorBag: String?
 }

 enum Result<T: Decodable> {
    case success(T)
    case error(withMessage: String)
 }
1

There are 1 best solutions below

0
On

You can try something like, which converts Single to Observable then call filterSuccessfulStatusAndRedirectCodes and you can handle the errors in catchError closure

func Request<T: Decodable>(_ request: APIManager) -> Observable<Result<T>> {
        self.sharedProvider.rx
                .request(request)
                .asObservable()
                .filterSuccessfulStatusAndRedirectCodes()
                .map(RequestResponse<T>.self)
                .map { Result.success }
                .catchError { error in
                    if let moyaError = error as? MoyaError {
                        return Objservable.error(handleNetworkError(withMoyaError: moyaError))
                    } else {
                        return Observable.error(error)
                    }
                 }
}