Hi, i have the following function inside my SessionaManager class which currently throws error to another class called NetworkManager which also takes a build request in the constructor and handle the errors thrown from this function.
public class NetworkSessionManager<T: Codable>: NetworkSession {
typealias GenericData = T?
//MARK: Properties
private let session: URLSession
//MARK: Manager Life Cycle
public init(session: URLSession = .shared) {
self.session = session
}
//MARK: Functions
internal func request(_ request: URLRequest) async throws -> SessionCompletionHandler {
return try await withCheckedThrowingContinuation { continuation in // 4
let dataTask = session.dataTask(with: request) { data, response, error in
var result: GenericData
guard error == nil else {
return continuation.resume(throwing: CustomErrors.responseContainsError)
}
guard let data = data, data.count > 0 else {
return continuation.resume(throwing: CustomErrors.responseDataUnwrappingFailed)
}
do {
// print("\n\n data from urlsession: \(data) \n\n")
// print("\n\n response from urlsession: \(response) \n\n")
// print("\n\n error from urlsession: \(error) \n\n")
result = try JSONDecoder().decode(GenericData.self, from: data)
continuation.resume(returning: (result, response))
} catch {
continuation.resume(throwing: CustomErrors.responseDataDecodingFailed)
}
}
dataTask.resume()
}
}
}
I am planning to remove the NetworkManager class and move the build request logic inside the SessionManager class because the NewotkrManager class is very little and does small things to justify its responsability.
Is there a way to handle errors directly withing the request function by replacing withCheckedThrowingContinuation with withCheckedContinuation without the need to throws errors to some caller functions or do i need to create an helper function inside the SessionManager class to handle the errors thrown by the request func after calling it?
Does the Continuation mechanism behaviour was built always to ensure that the Errors are always thrown to the caller function and handled by it taking into consideration that this is an async function and thus errors couldn't be handled directly within it?