Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Enhancement] Add DecodingError as associated type in decode enum case in ResponseError #1

Merged
merged 1 commit into from
May 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions Sources/CoreNetworking/HTTPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,20 @@ public class HTTPClient {
}
switch response.statusCode {
case 200...299:
guard let decodedResponse = try? jsonDecoder.decode(
responseType,
from: data
) else {
throw Request.RequestError.decode
do {
let decodedResponse = try jsonDecoder.decode(
responseType,
from: data
)

return decodedResponse
} catch {
guard let decodingError = error as? DecodingError else {
throw Request.RequestError.decode()
}

throw Request.RequestError.decode(decodingError)
}
return decodedResponse
case 401:
throw Request.RequestError.unauthorized
default:
Expand Down
6 changes: 3 additions & 3 deletions Sources/CoreNetworking/Request.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,15 @@ public extension Request {
}

enum RequestError: Error {
case decode
case decode(DecodingError? = nil)
case noResponse
case unauthorized
case unexpectedStatusCode

var customMessage: String {
switch self {
case .decode:
return "Decode error"
case .decode(let underlyingError):
return "Decode error: \(String(describing: underlyingError))"
case .unauthorized:
return "Session expired"
default:
Expand Down
11 changes: 10 additions & 1 deletion Tests/CoreNetworkingTests/CoreNetworkingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,17 @@ final class CoreNetworkingTests: XCTestCase {
do {
_ = try await service.fetchCatFact()
XCTFail("Should have thrown")
} catch let Request.RequestError.decode(DecodingError.keyNotFound(key, context)?) {
XCTAssertEqual(key.intValue, nil)
XCTAssertEqual(key.stringValue, "fact")
XCTAssertEqual(context.codingPath.count, 0)
XCTAssertEqual(
context.debugDescription,
"No value associated with key CodingKeys(stringValue: \"fact\", intValue: nil) (\"fact\")."
)
XCTAssertNil(context.underlyingError)
} catch {
XCTAssertEqual(error as? Request.RequestError, .decode)
XCTFail("Should have thrown RequestError.decode error")
}
}
}
Expand Down