Skip to content

Commit 36a1568

Browse files
committed
Created JSON error response in .mapIfError callback
1 parent e47014f commit 36a1568

File tree

1 file changed

+5
-17
lines changed

1 file changed

+5
-17
lines changed

Sources/APIErrorMiddleware/APIErrorMiddleware.swift

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -31,28 +31,16 @@ public final class APIErrorMiddleware: Middleware, Service, ServiceType {
3131
/// middleware futher down the responder chain and
3232
/// convert it to a JSON response.
3333
public func respond(to request: Request, chainingTo next: Responder) throws -> Future<Response> {
34-
35-
// We create a new promise that wraps a `Response` object.
36-
// No, there are not any initializers to do this.
37-
let result = request.eventLoop.newPromise(Response.self)
38-
34+
3935
// Call the next responder in the reponse chain.
4036
// If the future returned contains an error, or if
4137
// the next responder throws an error, catch it and
4238
// convert it to a JSON response.
43-
// If no error is found, succed the promise with the response
44-
// returned by the responder.
45-
do {
46-
try next.respond(to: request).do { response in
47-
result.succeed(result: response)
48-
}.catch { error in
49-
result.succeed(result: self.response(for: error, with: request))
50-
}
51-
} catch {
52-
result.succeed(result: self.response(for: error, with: request))
39+
return Future.flatMap(on: request) {
40+
return try next.respond(to: request)
41+
}.mapIfError { error in
42+
return self.response(for: error, with: request)
5343
}
54-
55-
return result.futureResult
5644
}
5745

5846
/// Creates a response with a JSON body.

0 commit comments

Comments
 (0)