title: Swift 5: Handling and decoding error of JSON
body: <p>Im running a service, which when I get an error it should show me the error message that comes from the backend. So far I have done this, and it works.</p>
  <p>However, I would like to know if it is possible to parse the back error in an enum for example, or something like that so that I would not have to call response.errors.result... But I can't understand how to do it to later obtain the string of the message that comes from the back in case of error.</p>
  <p>On the other hand, I have a question about whether it is possible not to have the default when the optional value is nil in the service. I mean the cases where I have to perform ?? ErrorMutation(code: 10, message: &quot;error&quot;) for example. If exist a way where i don't have to pass it a default value.</p>
  <pre><code>struct ResponseData: Codable {
      let data: Data?
      let errors: Errors?
  }
  </code></pre>
  <hr />
  <pre><code>struct Data: Codable {
      let result: Mutation?
  }
  </code></pre>
  <hr />
  <pre><code>struct Mutation: Codable {
      let id: String?
      let active: Bool?
  }
  </code></pre>
  <hr />
  <pre><code>struct Errors: Codable, Error {
      let result: [ErrorMutation]?
  }
  </code></pre>
  <hr />
  <pre><code>struct ErrorMutation: Codable, Error {
      let code: Int?
      let message: String?
  }
  </code></pre>
  <hr />
  <pre><code>final class MutationManager: Service {
      func getTDMutation() -&gt; Observable&lt;Result&lt;Mutation, ErrorMutation&gt;&gt; {
          let mutationQuery = Bundle.main.value ?? &quot;&quot;
          let body = [&quot;query&quot;: &quot;mutation \(mutationQuery)&quot;]
          return response(body: body)
              .map {
                  try JSONDecoder().decode(ResponseData.self, from: $0) }
              .flatMap { response -&gt; Observable&lt;Result&lt;Mutation, ErrorMutation&gt;&gt; in
                  guard response.data != nil else {
                      let error = response.errors?.result.first
                      return .just(.failure(error ?? ErrorMutation(code: 10, message: &quot;error&quot;)))
                  }
                  return .just(.success(response.data?.result ?? Mutation(id: &quot;&quot;, active: false)))
              }
      }
  }
  </code></pre>