我正在将 Moya 与 RxSwift 一起用于 iOS 应用程序中的网络,并且我希望能够在我Observer
的 s 调用时使用我的 API 的自定义错误响应onError
。
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)")
}
}