Last active
March 10, 2025 18:58
-
-
Save hmlongco/d94dcea1f6997bf5d73932559b0ee22b to your computer and use it in GitHub Desktop.
DecodingError.swift
This file contains hidden or 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
// instead of "nested" try catches... | |
public func load() async throws -> [FeedItem] { | |
do { | |
let (data, response) = try await client.get(from: url) | |
guard let httpResponse = response as? HTTPURLResponse else { | |
throw Error.invalidData | |
} | |
guard httpResponse.statusCode == 200 else { | |
throw NetworkError.badStatus(httpResponse.statusCode) | |
} | |
do { | |
let decoder = JSONDecoder() | |
let items = try decoder.decode([FeedItem].self, from: data) | |
return items | |
} catch { | |
throw Error.invalidData | |
} | |
} catch { | |
throw Error.connectivity | |
} | |
} | |
// do | |
public func load() async throws -> [FeedItem] { | |
do { | |
let (data, response) = try await client.get(from: url) | |
guard let httpResponse = response as? HTTPURLResponse else { | |
throw Error.invalidData | |
} | |
guard httpResponse.statusCode == 200 else { | |
throw NetworkError.badStatus(httpResponse.statusCode) | |
} | |
return try JSONDecoder().decode([FeedItem].self, from: data) | |
} catch is DecodingError { | |
throw Error.invalidData | |
} catch { | |
throw Error.connectivity | |
} | |
} | |
// no nesting or messy switch statements needed | |
// also a better onSuccess/failure handler | |
extension Result { | |
func onSuccess(_ handler: (Success) -> Void, failure: (Failure) -> Void) -> Self { | |
switch self { | |
case .success(let value): | |
handler(value) | |
case .failure(let error): | |
failure(error) | |
} | |
return self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment