diff --git a/Sources/HTTPMock/Models/MockResponse.swift b/Sources/HTTPMock/Models/MockResponse.swift index 383b870..378f757 100644 --- a/Sources/HTTPMock/Models/MockResponse.swift +++ b/Sources/HTTPMock/Models/MockResponse.swift @@ -46,15 +46,24 @@ extension MockResponse { delivery: Delivery = .instant, headers: [String: String] = [:], jsonEncoder: JSONEncoder = .mockDefault - ) throws -> MockResponse { - let data = try jsonEncoder.encode(payload) - return Self.init( - payload: .data(data, contentType: "application/json"), - status: status, - lifetime: lifetime, - delivery: delivery, - headers: headers - ) + ) -> MockResponse { + do { + let data = try jsonEncoder.encode(payload) + return Self.init( + payload: .data(data, contentType: "application/json"), + status: status, + lifetime: lifetime, + delivery: delivery, + headers: headers + ) + } catch { + HTTPMockLog.error(""" + Failed to encode payload to JSON data. Fallback to `.empty()`. + Payload: \(payload) + Error: \(error) + """) + return .empty() + } } public static func dictionary( @@ -63,15 +72,24 @@ extension MockResponse { lifetime: Lifetime = .single, delivery: Delivery = .instant, headers: [String: String] = [:] - ) throws -> MockResponse { - let data = try JSONSerialization.data(withJSONObject: payload) - return Self.init( - payload: .data(data, contentType: "application/json"), - status: status, - lifetime: lifetime, - delivery: delivery, - headers: headers - ) + ) -> MockResponse { + do { + let data = try JSONSerialization.data(withJSONObject: payload) + return Self.init( + payload: .data(data, contentType: "application/json"), + status: status, + lifetime: lifetime, + delivery: delivery, + headers: headers + ) + } catch { + HTTPMockLog.error(""" + Failed to serialize payload to JSON data. Fallback to `.empty()`. + Payload: \(payload) + Error: \(error) + """) + return .empty() + } } public static func plaintext( diff --git a/Tests/HTTPMockTests/HTTPMockTests.swift b/Tests/HTTPMockTests/HTTPMockTests.swift index 3c24d4e..a69f3a8 100644 --- a/Tests/HTTPMockTests/HTTPMockTests.swift +++ b/Tests/HTTPMockTests/HTTPMockTests.swift @@ -157,13 +157,13 @@ struct HTTPMockTests { } @Test - func itSetsDefaultContentTypeAndAllowsOverride() throws { + func itSetsDefaultContentTypeAndAllowsOverride() { // `plaintext` default let plainText = MockResponse.plaintext("hi") #expect(plainText.headers["Content-Type"] == "text/plain") // `encodable` default - let encodable = try MockResponse.encodable(DummyData()) + let encodable = MockResponse.encodable(DummyData()) #expect(encodable.headers["Content-Type"] == "application/json") // Override content type via explicit headers