Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ankittlp/05c32834c742928726ad9b3d493b52a3 to your computer and use it in GitHub Desktop.
Save ankittlp/05c32834c742928726ad9b3d493b52a3 to your computer and use it in GitHub Desktop.
URLSessionDataTaskPublisher_ErrorHandling
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