Hello. I’m loving http4k but I noticed I’m not hav...
# http4k
b
Hello. I’m loving http4k but I noticed I’m not having luck with exception handling. Normally, when you have an uncaught exception, it will eventually get logged. That doesn’t seem to be happening. I’m using Undertow as my server, but I’m not sure that matters. I saw the
CatchAll
filter, but I it looks like that logs the stacktrace to the response, which is not what I would expect or want. I want a 500 status returned on uncaught exception, but I also want a log with the stacktrace. Sure, I can implement this myself with a filter, but I just feel like I’m missing some important piece of the puzzle. Please advise on how to approach exceptions (there will always be exceptions we don’t anticipate, and I want to make sure that these get logged so that in a production system, I can see the stacktrace).
r
If you look at http4k it does not uses logs (no dep to slf4j-api), is up to you to add the log lib you want and handle them as you like. They provide a way to use Structured Logging with Events but it's up to you to handle them and call it, You can easly do it by creating a filter (check CatchAll one) and do the logging and handle the exceptions response as you like,
👀 1
Also, you should never use CatchAll in production code, not a great idea risking to expose the stacktrace.
f
Something like this would work for what you're after:
Copy code
object ErrorLoggingCatchAll {
        operator fun invoke(errorStatus: Status = INTERNAL_SERVER_ERROR): Filter = Filter { next ->
            {
                try {
                    next(it)
                } catch (e: Exception) {
                   log.error("Some error text here", e)
                 Response(errorStatus).body("some error message")
                }
            }
        }
    }
b
Thanks @fredrik.nordin and @Razvan. This is what I was thinking, but its great to have this confirmed from you, so I know I’m not going the wrong path. Appreciate it.
👍 1