Custom Error Response Handling with Moya + RxSwift
<p>I'm using Moya with RxSwift for networking in an iOS app, and I'd like to be able to consume my API's custom error responses when my <code>Observer</code>s get calls to <code>onError</code>.</p>

<p>The API always returns error responses in the following JSON format:</p>

<pre><code>{
   "error": {
      "message": "Error message goes here",
      "code": "String error code"
   }
}
</code></pre>

<p><strong>The goal is to achieve something similar to the following code snippet, where the error passed in <code>onError</code> is my custom error type instead of the <code>Moya.Error</code> type:</strong></p>

<pre><code>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)")
        })
</code></pre>

<p>I'm able to successfully intercept and deserialize these errors into my custom error model using a custom <code>PluginType</code> (pasted below, from <a href="https://stackoverflow.com/questions/34706689/how-to-handle-the-response-of-all-types-of-requests-in-one-handler-but-also-uni">this SO question</a>), but I do not know how to finally pass these models along to the <code>Observer</code>. </p>

<pre><code>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&lt;Moya.Response, Moya.Error&gt;, target: TargetType) {
    let responseJSON: AnyObject
    if let response = result.value {
        do {
            responseJSON = try response.mapJSON()
            if let errorResponse = Mapper&lt;MyCustomErrorModel&gt;().map(responseJSON) {
                print("Custom error code from server: \(errorResponse.error?.code)")
            }
        } catch {
            print("Failure to parse JSON response")
        }
    } else {
        print("Network Error = \(result.error)")
    }
}
</code></pre>