Created
September 27, 2021 13:21
-
-
Save anhar/dbe71d3424ea2868f71357298486d397 to your computer and use it in GitHub Desktop.
Improved error handling on top of tundsdev async/await example on YouTube: https://youtu.be/53lbqYYAPLw
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
// | |
// CharactersService.swift | |
// RickAndMortyApp | |
// | |
// Created by Andreas Hård on 2021-09-27. | |
// | |
import Foundation | |
struct CharactersService { | |
let decoder: JSONDecoder | |
let endpointURL: URL = .init(string: "https://rickandmortyapi.com/api/character")! | |
init(decoder: JSONDecoder) { | |
self.decoder = decoder | |
} | |
func fetchCharacters() async -> FetchCharactersResult { | |
do { | |
let (data, response) = try await URLSession.shared.data(from: endpointURL) | |
guard let response: HTTPURLResponse = response as? HTTPURLResponse else { | |
let error: FetchCharactersError = .failedToGetHTTPURLResponse | |
return .failure(error) | |
} | |
guard response.statusCode == 200 else { | |
let error: FetchCharactersError = .invalidStatusCode(statusCode: response.statusCode) | |
return .failure(error) | |
} | |
do { | |
let response: CharactersResponseModel = try decoder.decode(CharactersResponseModel.self, from: data) | |
return .success(response.results) | |
} catch { | |
let error: FetchCharactersError = .decodeError(error: error) | |
return .failure(error) | |
} | |
} catch { | |
let error: FetchCharactersError = .urlSessionError(error: error) | |
return .failure(error) | |
} | |
} | |
} | |
extension CharactersService { | |
typealias FetchCharactersResult = Result<[CharactersResponseModel.Character], FetchCharactersError> | |
enum FetchCharactersError: Error { | |
case urlSessionError(error: Error) | |
case failedToGetHTTPURLResponse | |
case invalidStatusCode(statusCode: Int) | |
case decodeError(error: Error) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improvements to the code:
JSONDecoder
to the struct so it doesn't have to be instantiated each time the function is calledfetchCharacters()
method to have a clear category of what types of errors can occur in the dedicatedFetchCharactersError
returned in theFetchCharactersResult