iosswiftalamofirenserror

How do I get at the underlying Error from an Alamofire error?


For this request:

Alamofire.request("https://google.com").responseCollection { (response: DataResponse<[User]>) in
  guard response.result.isSuccess else {
    print(response.error)

    return
  }
}

I see this printed in the console:

Optional(my_app_name.BackendError.jsonSerialization(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))))

What I've tried:

Alamofire.request("https://google.com").responseCollection { (response: DataResponse<[User]>) in
  guard response.result.isSuccess else {
    print(response.error)

    if let error1 = response.error as? AFError {
      print(error1)  // Execution DOES NOT reach here.
    }

    if let error2 = response.error as? BackendError {
      print(error2) // Execution DOES reach here.
    }

    return
  }
}

print(error2) above prints:

jsonSerialization(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))

What I'm trying to do is get at the underlying error so I can parse the domain, code, and userInfo properties.

I created the BackendError enum that Alamofire provides as an example at https://github.com/Alamofire/Alamofire#handling-errors :

enum BackendError: Error {
    case network(error: Error) // Capture any underlying Error from the URLSession API
    case dataSerialization(error: Error)
    case jsonSerialization(error: Error)
    case xmlSerialization(error: Error)
    case objectSerialization(reason: String)
}

and I also implemented the example generic response object serialization exactly like the example at https://github.com/Alamofire/Alamofire#generic-response-object-serialization :

extension DataRequest {
  @discardableResult
  func responseCollection<T: ResponseCollectionSerializable>(
    queue: DispatchQueue? = nil,
    completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self {
    let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in
      guard error == nil else {
        return .failure(BackendError.network(error: error!))
      }

      let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
      let result = jsonSerializer.serializeResponse(request, response, data, nil)

      guard case let .success(jsonObject) = result else {
        return .failure(BackendError.jsonSerialization(error: result.error!))
      }

      guard let response = response else {
        let reason = "Response collection could not be serialized due to nil response."
        return .failure(BackendError.objectSerialization(reason: reason))
      }

      return .success(T.collection(from: response, withRepresentation: jsonObject))
    }

    return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
  }
}

I think there are switches, cases, and casts to and from BackendError, AFError, Error, and/or NSError, but I can't seem to get it.

How can I get at the underlying error so I can parse the domain, code, and userInfo properties?

I'm using Swift 3 and Alamofire 4.3.0 .


Solution

  • For Alamofire 4.3, look at response.result:

    if case let .failure(error) = response.result {
        let error = error as NSError
        print("\(error.domain)")
        print("\(error.code)")
        print("\(error.userInfo)")
    }