0

I have a Java function, say method1(), which throws an exception upon some condition, say condition A. I'm calling that function from my FTL file with condition A met. Now I'm getting a template error in FTL saying above function threw an exception. Just like we handle exceptions in Java with try-catch, I want something similar in my FTL.

This is something similar to my FTL code.

<#-- @ftlvariable name="someUtilClass" type="com.some.package.SomeUtilClass" -->

    <#attempt>
        <#assign x = someUtilClass.method1() />
    <#recover>
        <#assign x = '' />
    </#recover>

I'm using Freemarker 2.3.20.

Thanks.

sam100rav
  • 3,733
  • 4
  • 27
  • 43
  • This may be related : http://stackoverflow.com/questions/15123743/what-are-different-ways-to-handle-error-in-freemarker-template – Arnaud Dec 06 '16 at 09:24
  • @Berger Actually I don't want to handle it in Java side, and attempt-recover is not working. – sam100rav Dec 06 '16 at 09:26
  • I may be wrong, but AFAIK you can't directly use Java code inside a Freemarker template. You need to use TemplateMethod to make it available as a method variable etc. so, if you haven't done that, it may be the reason why _attemp-recover is not working_. Are you sure your FTL code is similar to that? – walen Dec 09 '16 at 10:01

1 Answers1

1

You aren't supposed to handle exceptions in a template, and unless we count #attempt-#recover in, there's no template language feature for that.

As of #attempt-#recover, it does catch the exception (I assume), so I'm not sure what you mean when you say that it's not working. However, if throwing that exception is part of normal operation, it won't be a fitting solution, as it will log it as an error before allowing the template processing to continue. Also it catches all kind of exceptions, not just the one that you normally expect. It's for failure scenarios, where you don't want the whole page to be down just because the service behind some panels of it is failing.

ddekany
  • 29,656
  • 4
  • 57
  • 64
  • As I said `#attempt` is not what you want anyway... or I guess not. But what goes wrong with that sample code? – ddekany Dec 09 '16 at 21:40
  • When the method throws an exception, x is not assigned empty string, instead ftl error is shown. – sam100rav Dec 11 '16 at 16:19
  • That's very strange. It works for me (though I'm using FreeMarker 2.3.25). A minimal but complete example to reproduce it would be welcome. – ddekany Dec 11 '16 at 23:31