Skip to content

Commit

Permalink
HTTPClient: also parse errors with application/json;charset=utf8 (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
NachoSoto authored Aug 17, 2023
1 parent dd5b76b commit 75c0d03
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
3 changes: 2 additions & 1 deletion Sources/Networking/HTTPClient/HTTPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -604,7 +604,8 @@ private extension VerifiedHTTPResponse {
private extension HTTPResponse where Body == Data {

func parseUnsuccessfulResponse() -> NetworkError {
let isJSON = self.value(forHeaderField: HTTPClient.ResponseHeader.contentType) == "application/json"
let contentType = self.value(forHeaderField: HTTPClient.ResponseHeader.contentType) ?? ""
let isJSON = contentType.starts(with: "application/json")

return .errorResponse(
isJSON
Expand Down
33 changes: 33 additions & 0 deletions Tests/UnitTests/Networking/HTTPClientTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,39 @@ final class HTTPClientTests: BaseHTTPClientTests<MockETagManager> {
expect(self.signing.requests).to(beEmpty())
}

func testServerSide500sWithCharsetContentType() throws {
let request = HTTPRequest(method: .get, path: .mockPath)
let errorCode = 500 + Int.random(in: 0..<50)

stub(condition: isPath(request.path)) { _ in
let json = "{\"code\": 5000,\"message\": \"something is broken up in the cloud\"}"
return HTTPStubsResponse(
data: json.asData,
statusCode: Int32(errorCode),
headers: [
HTTPClient.ResponseHeader.contentType.rawValue: "application/json;charset=utf8"
]
)
}

let result = waitUntilValue { completion in
self.client.perform(request) { (response: DataResponse) in
completion(response)
}
}

expect(result).to(beFailure())
let error = try XCTUnwrap(result?.error)

expect(error) == .errorResponse(
.init(code: .unknownBackendError,
originalCode: 5000,
message: "something is broken up in the cloud"),
HTTPStatusCode(rawValue: errorCode)
)
expect(error.isServerDown) == true
}

func testServerSide500sWithUnknownBody() throws {
let request = HTTPRequest(method: .get, path: .mockPath)
let errorCode = 500 + Int.random(in: 0..<50)
Expand Down

0 comments on commit 75c0d03

Please sign in to comment.