Last active
May 7, 2022 20:51
-
-
Save ankittlp/05c32834c742928726ad9b3d493b52a3 to your computer and use it in GitHub Desktop.
URLSessionDataTaskPublisher_ErrorHandling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum APIError: Error, LocalizedError { | |
case invalidServerResponse | |
case unknown | |
var errorDescription: String? { | |
switch self { | |
case .unknown: | |
return "Unknown error" | |
case .invalidServerResponse: | |
return "Invalid Server Response" | |
} | |
} | |
} | |
enum ParseError: Error, LocalizedError { | |
case parserError(reason: String) | |
var errorDescription: String? { | |
switch self { | |
case .parserError(let reason): | |
return reason | |
} | |
} | |
} | |
//let url = URL(string: "https://api.github.com/users/hadley/orgs")! | |
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")! | |
let cancellable = URLSession.shared.dataTaskPublisher(for: url) | |
// 1 | |
.tryMap { data, response -> Data in | |
guard let httpResponse = response as? HTTPURLResponse, | |
httpResponse.statusCode == 200 else { | |
throw APIError.invalidServerResponse | |
} | |
return data | |
} | |
// 2 | |
/*.tryMap({ data in | |
return try JSONDecoder().decode([Post].self, from: data) | |
})*/ | |
.decode(type: [Post].self, decoder: JSONDecoder()) | |
// 3 | |
.mapError({ error -> Error in | |
if let error = error as? APIError { | |
return error | |
} else if error is DecodingError { | |
return ParseError.parserError(reason: error.localizedDescription) | |
} else { | |
return APIError.unknown | |
} | |
}) | |
.eraseToAnyPublisher() | |
.sink { completion in | |
print(".sink() received the completion", String(describing: completion)) | |
switch completion { | |
case .finished: | |
break | |
case .failure(let anError): | |
print("received error: ", anError) | |
} | |
} receiveValue: { posts in | |
print(".sink() received \(posts)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment