brokenhandsio/leaf-error-middleware

How to use with a specific route?

tonyarnold opened this issue · 7 comments

I'd like to host both API and public web endpoints in a single app, but I don't want HTML error pages for my API endpoints.

I've tried the following, without registering against the default middlewares:

router.grouped(LeafErrorMiddleware.self)

But it doesn't work.

You can create a custom middleware like that

`final class CustomMiddleware: Middleware {

func respond(to request: Request, chainingTo next: Responder) throws -> EventLoopFuture {
let isAPI = request.http.url.path.starts(with: "/v1")

let response: Future<Response>
do {
    response = try next.respond(to: request)
} catch {
    response = request.eventLoop.newFailedFuture(error: error)
}

return response.catchFlatMap { error in
  isAPI ? try self.apiError(forResponse: response) : try self.webError(forRequest: request, chainingTo: next)
}

}

}`

Shouldn't it be possible to just register the middleware against a specific route group? (rather than hard coding endpoint URL exclusions)

0xTim commented

@tonyarnold when you say it doesn't work, what error's do you encounter?

There's no error, the middleware just isn't called. This could totally be a misunderstanding of how things work on my part - to date, I've not had much luck getting any error-handling middleware to work on just a specific group of routes. I alway seem to need to register it globally in configure(…).

0xTim commented

I can see why it wouldn't work, but the compiler shouldn't let you use it if it doesn't work. Does router.grouped(LeafErrorMiddleware(environment: Environment.detect()) work?

Yeah, still nothing even when manually initialising like you've shown. I'll try to pull together a reduced reproduction over the weekend. I just get the following in the logs:

[ ERROR ] Abort.404: Not Found (ApplicationResponder.swift:50)
[ ERROR ] Abort.404: Not Found (ApplicationResponder.swift:50)
[ ERROR ] Abort.404: Not Found (ApplicationResponder.swift:50)
[ ERROR ] Abort.404: Not Found (ApplicationResponder.swift:50)
0xTim commented

Ok manually initialising it and it not being called is definitely a bug