planety / prologue

Powerful and flexible web framework written in Nim
https://planety.github.io/prologue
Apache License 2.0
1.24k stars 47 forks source link

Feature Request: Middleware to map exceptions to response status codes #206

Open PhilippMDoerner opened 1 year ago

PhilippMDoerner commented 1 year ago

Currently, when an exception occurs in a handler and it bubbles up beyond the handler-proc itself, prologue will always return an HTTP500.

But what if I have a custom FormValidationException and always, globally, want to return an HTTP400 response if that occurs, maybe even with a specific message? I would have to wrap every handler in a custom try-catch block.

I think it would be better if we had a middleware, where the user provides a Table that maps Exceptions to Status-codes. Then the middleware could catch all exceptions, map the exception to the status code it belongs to and call the default response for that Status code, it could also log the occurrence of the exception. That table could maybe even contain a string in addition to the status-code, or an option could be provided if exception messages should be forwarded as part of the response body.

defaultErrorHandlers do exist, but they don't apply here. As far as I've understood them, they define what the response should look like if you respond with a given HTTP code. This does not map exception --> output though, this maps HTTP error code --> output. I want to have a mapping of exceptionType --> HTTP error code.

The biggest question for me is, whether such a middleware should be provided as part of prologue or not. Should this not make the cut to be one of prologue's provided middlewares, it could be its own package I believe.