Skip to content

Commit 2025900

Browse files
committed
Created default error for encoding failure
1 parent 36a1568 commit 2025900

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

Sources/APIErrorMiddleware/APIErrorMiddleware.swift

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,10 +102,15 @@ public final class APIErrorMiddleware: Middleware, Service, ServiceType {
102102
}
103103
}
104104

105-
// Create JSON with an `error` key with the `message` constant as its value.
106-
// We default to no data instead of throwing, because we don't want any errors
107-
// leaving the middleware body.
108-
let json = (try? JSONEncoder().encode(["error": result.message])) ?? result.message.data(using: .utf8) ?? Data()
105+
let json: Data
106+
do {
107+
// Create JSON with an `error` key with the `message` constant as its value.
108+
json = try JSONEncoder().encode(["error": result.message])
109+
} catch {
110+
// Creating JSON data from error failed, so create a generic response message
111+
// because we can't have any Swift errors leaving the middleware.
112+
json = Data("{\"error\": \"Unable to encode error to JSON\"}".utf8)
113+
}
109114

110115
// Create an HTTPResponse with
111116
// - The detected status code, using

0 commit comments

Comments
 (0)