Skip to content

Instantly share code, notes, and snippets.

@anhar
Created September 27, 2021 13:21
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 anhar/dbe71d3424ea2868f71357298486d397 to your computer and use it in GitHub Desktop.
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
//
// 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)
}
}
@anhar
Copy link
Author

anhar commented Sep 27, 2021

Improvements to the code:

  • Adding the JSONDecoder to the struct so it doesn't have to be instantiated each time the function is called
  • Removing the throwing of the fetchCharacters() method to have a clear category of what types of errors can occur in the dedicated FetchCharactersError returned in the FetchCharactersResult

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment