wimdeblauwe / htmx-spring-boot

Spring Boot and Thymeleaf helpers for working with htmx
Apache License 2.0
423 stars 41 forks source link

Allow HtmxResponse to be used as return type in error handlers #95

Closed wimdeblauwe closed 6 months ago

wimdeblauwe commented 7 months ago

This PR adds an HandlerMethodReturnValueHandler implementation to handle a HtmxResponse object as a return type from an error handler. A lot of code is the same as in HtmxViewHandlerInterceptor. For that reason, I extracted HtmxResponseHelper.

@dsyer and @odrotbohm Would love you feedback on this PR. Especially doubting if the method calls I am doing in the HtmxMvcAutoConfiguration are correct given that @AutoConfiguration has proxyBeanMethods set to false, but I don't know of another way to make it work.

Fixes #94

dsyer commented 7 months ago

Agree about the internal method call. We either need to remove the proxyBeanMethods flag or ship them out to a separate @Configuration (and wire them back into the constructor).

dsyer commented 7 months ago

Isn’t the interceptor mainly doing exactly the same work as the return value handler? I’m not sure it needs to be done twice. (So all the code from the helper could just be migrated to the return value handler?)

wimdeblauwe commented 7 months ago

Thanks for the input @dsyer. You are correct that there is no more need for the intercepter, the return value handler works for all cases. I have updated the code accordingly.

dsyer commented 7 months ago

LGTM

wimdeblauwe commented 6 months ago

This is now released and I blogged to showcase the feature: https://www.wimdeblauwe.com/blog/2023/12/14/htmx-global-error-handler/

xhaggi commented 5 months ago

@wimdeblauwe is there a way to restrict the @ExceptionHandler to htmx requests only?

wimdeblauwe commented 5 months ago

According to https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc/, you can define a HttpServletRequest parameter in your exception handler. You could read the headers there to check if it is an htmx request or not.

xhaggi commented 5 months ago

Yeah, I am aware of that. I meant an annotation like the one we have for the controller methods.

wimdeblauwe commented 5 months ago

That would be nice if that is possible, but no clue if there are extension points to implement that.