casid / jte

Secure and speedy templates for Java and Kotlin.
https://jte.gg
Apache License 2.0
844 stars 63 forks source link

Message from TemplateNotFoundException is "lost" #397

Open nilshartmann opened 1 month ago

nilshartmann commented 1 month ago

When the TemplateEngine tries to load a template that cannot be found, the origin TemplateNotFoundException is not logged anywhere. That's a little sad, because the message contains the actual path, the engine tried to load the template from, and that information is very helpful when trying to investigate, why the template could not be loaded.

In gg.jte.TemplateEngine#resolveTemplateOnDemand it is caught, then re-thrown and in finally caught in gg.jte.TemplateEngine#hasTemplate, where the caugt exception is interpreted as false (template does not exists).

 public boolean hasTemplate(String name) {
        try {
            resolveTemplate(name);
            return true;
        } catch (TemplateNotFoundException e) {

           // helpful information in e.getMessage(), but unfortunately lost here :-/
            return false;
        }
    }

I wonder, if somewhere in between this very helpful message could be logged to simplify bug fixing.

casid commented 1 month ago

Hi @nilshartmann, thank you for reporting!

When using jte directly, this should already be the case, since the render() method should throw this exception when rendering a template that cannot be found.

I assume you are using the spring boot plugin? The hasTemplate method is used in gg.jte.springframework.boot.autoconfigure.JteView#checkResource.

Check whether the underlying resource that the configured URL points to actually exists.
Params:
locale – the desired Locale that we're looking for
Returns:
true if the resource exists (or is assumed to exist); false if we know that it does not exist
Throws:
Exception – if the resource exists but is invalid (e. g. could not be parsed)

Reading the contract, this method seems to behave as expected (does not throw if resource does not exist).

We could add something like this to jte:

public void checkTemplateExists(String name) throws TemplateNotFoundException {
    resolveTemplate(name);
}

And then catch and log the exception in gg.jte.springframework.boot.autoconfigure.JteView#checkResource.

@atomfrede, @tschuehly do you know if there is a way to log messages in the spring boot plugin?

nilshartmann commented 1 month ago

@casid Yes, you're right, I'm using the Spring Boot starter (for some reason I removed this info from my description 🤦‍♂️)

I think the method behaves correctly but it would be nice to somehow see the original error message.

atomfrede commented 1 month ago

Good point. Let me check how others starters behave, but totally agree at least see the message would be helpful, on particular for typos