RxMoya网络和服务错误处理功能相同

时间:2018-09-23 08:24:06

标签: ios error-handling observable rx-swift moya

我正在尝试实现处理网络和API错误的函数,我的问题是如何在filterSuccessfulStatusCodes()之后再次发出可观察对象。 我遇到的主要问题是,在第一次订阅后,我不确定这种方法是否正确。

此代码中的当前错误是:调用中额外的参数'onError'

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)
 }

2 个答案:

答案 0 :(得分:1)

这是我的初始功能,效果很好,但是我无法理解如何进行网络和api错误检查。

func getA(_ request: APIManager) -> Observable<Result<[A]>> {
    return request(request)
}

func request<T: Decodable>(_ request: APIManager) -> Observable<Result<T>> {
    return provider.rx
        .request(request)
        .map(RequestResponse<T>.self)
        .map { $0.result! }
        .asObservable()
        .map(Result.success)
        .catchError { error in
            return .just(.error(withMessage: "Failed \(error)"))
    }
}

答案 1 :(得分:0)

您可以尝试将Single转换为Observable然后调用filterSuccessfulStatusAndRedirectCodes的方法,然后处理catchError闭包中的错误

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)
                    }
                 }
}