Skip to content

Commit 46cb3f4

Browse files
committed
Fix the fact that error might not be JSON
1 parent 46f35cb commit 46cb3f4

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

Sources/Hummingbird/Error/HTTPError.swift

+5-14
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,8 @@ import NIOFoundationCompat
2020
public struct HTTPError: Error, HTTPResponseError, Sendable {
2121
/// status code for the error
2222
public var status: HTTPResponse.Status
23-
/// internal representation of error headers without contentType
24-
private var _headers: HTTPFields
25-
/// headers
26-
public var headers: HTTPFields {
27-
get {
28-
return self.body != nil ? self._headers + [.contentType: "application/json; charset=utf-8"] : self._headers
29-
}
30-
set {
31-
self._headers = newValue
32-
}
33-
}
23+
/// response headers
24+
public var headers: HTTPFields
3425

3526
/// error message
3627
public var body: String?
@@ -40,7 +31,7 @@ public struct HTTPError: Error, HTTPResponseError, Sendable {
4031
/// - status: HTTP status
4132
public init(_ status: HTTPResponse.Status) {
4233
self.status = status
43-
self._headers = [:]
34+
self.headers = [:]
4435
self.body = nil
4536
}
4637

@@ -50,7 +41,7 @@ public struct HTTPError: Error, HTTPResponseError, Sendable {
5041
/// - message: Associated message
5142
public init(_ status: HTTPResponse.Status, message: String) {
5243
self.status = status
53-
self._headers = [:]
44+
self.headers = [:]
5445
self.body = message
5546
}
5647

@@ -61,7 +52,7 @@ public struct HTTPError: Error, HTTPResponseError, Sendable {
6152
/// - message: Optional associated message
6253
public init(_ status: HTTPResponse.Status, headers: HTTPFields, message: String? = nil) {
6354
self.status = status
64-
self._headers = headers
55+
self.headers = headers
6556
self.body = message
6657
}
6758

Tests/HummingbirdTests/URLEncodedForm/Application+URLEncodedFormTests.swift

+15
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,19 @@ final class HummingBirdURLEncodedTests: XCTestCase {
7171
}
7272
}
7373
}
74+
75+
func testError() async throws {
76+
let router = Router(context: URLEncodedCodingRequestContext.self)
77+
router.get("/error") { _, _ -> User in
78+
throw HTTPError(.badRequest, message: "Bad Request")
79+
}
80+
let app = Application(responder: router.buildResponder())
81+
try await app.test(.router) { client in
82+
try await client.execute(uri: "/error", method: .get) { response in
83+
XCTAssertEqual(response.status, .badRequest)
84+
XCTAssertEqual(response.headers[.contentType], "application/x-www-form-urlencoded")
85+
XCTAssertEqual(String(buffer: response.body), "error[message]=Bad%20Request")
86+
}
87+
}
88+
}
7489
}

0 commit comments

Comments
 (0)