使用Moya + RxSwift进行自定义错误响应处理

时间:2016-08-27 19:46:38

标签: ios swift rx-swift objectmapper moya

我正在使用Moya与RxSwift在iOS应用中建立联网,我希望能够在Observer拨打onError时使用我的API自定义错误响应。< / p>

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

1 个答案:

答案 0 :(得分:3)

我建议扩展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)