Skip to content

Commit c2cd5b7

Browse files
authored
Merge branch 'main' into persist-expires
2 parents 0073f13 + 609f1d7 commit c2cd5b7

File tree

2 files changed

+30
-13
lines changed

2 files changed

+30
-13
lines changed

Sources/Hummingbird/Error/HTTPError.swift

+15-13
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,18 @@ 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 = [:]
45+
self.body = message
46+
}
47+
48+
/// Initialize HTTPError
49+
/// - Parameters:
50+
/// - status: HTTP status
51+
/// - headers: Headers to include in error
52+
/// - message: Optional associated message
53+
public init(_ status: HTTPResponse.Status, headers: HTTPFields, message: String? = nil) {
54+
self.status = status
55+
self.headers = headers
5456
self.body = message
5557
}
5658

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)