gpt4 book ai didi

ios - 使用 Moya + RxSwift 自定义错误响应处理

转载 作者:搜寻专家 更新时间:2023-10-31 19:29:26 24 4
gpt4 key购买 nike

我在 iOS 应用程序中使用 Moya 和 RxSwift 进行网络连接,我希望能够在我的 Observer 调用 onError 时使用我的 API 的自定义错误响应

API 始终以以下 JSON 格式返回错误响应:

{
"error": {
"message": "Error message goes here",
"code": "String error code"
}
}

目标是实现类似于下面的代码片段,其中 onError 中传递的错误是我自定义的错误类型,而不是 Moya.Error输入:

observable
.subscribe(
onNext: { response in
// Do typical onNext stuff
},
onError: { error in
// Get and consume my custom error type here:
let customError = error as! MyCustomErrorModel
print("My API's error message: \(customError.error?.message)")
print("My API's error code: \(customError.error?.code)")
})

我能够使用自定义 PluginType(粘贴在下面,来自 this SO question)成功拦截这些错误并将其反序列化到我的自定义错误模型中,但我不知道如何最终传递这些错误沿 Observer 建模。

import Foundation
import Moya
import ObjectMapper
import Result

struct CustomAPIErrorPlugin: PluginType {

// Called immediately before a request is sent over the network (or stubbed).
func willSendRequest(request: RequestType, target: TargetType) { }

// Called after a response has been received, but before the MoyaProvider has invoked its completion handler.
func didReceiveResponse(result: Result<Moya.Response, Moya.Error>, target: TargetType) {
let responseJSON: AnyObject
if let response = result.value {
do {
responseJSON = try response.mapJSON()
if let errorResponse = Mapper<MyCustomErrorModel>().map(responseJSON) {
print("Custom error code from server: \(errorResponse.error?.code)")
}
} catch {
print("Failure to parse JSON response")
}
} else {
print("Network Error = \(result.error)")
}
}

最佳答案

我建议扩展 ObservableType,因为当我们谈论处理 api 错误响应时,这最终是最干净的解决方案。如下所示(未测试...)

extension ObservableType where E == Response {
func filterSuccess() -> Observable<E> {
return flatMap { (response) -> Observable<E> in
if 200 ... 299 ~= response.statusCode {
return Observable.just(response)
}

if let errorJson = response.data.toJson(),
let error = Mapper<MyCustomErrorModel>().map(errorJson) {
return Observable.error(error)
}

// Its an error and can't decode error details from server, push generic message
let genericError = MyCustomErrorModel.genericError(code: response.statusCode, message: "Unknown Error")
return Observable.error(genericError)
}
}

这就是你使用它的方式

provider.request(.test)
.filterSuccess()
.mapJSON()
.subscribe { [unowned self] e in
switch e {
case .next(let json as JSON):
case .error(let error as MyCustomErrorModel):
// Handle your custom error here
default: break
}
}.disposed(by: disposeBag)

关于ios - 使用 Moya + RxSwift 自定义错误响应处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39185109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com