How to fail Velocity template processing with tracable message

Viewed 574

Having:

  • Velocity template or macro
  • some object

How to validate the object (#if) and fail (stop further processing) in a way that is easily tracable to the place of failure (like throwing exception in Java).

I am looking for something like this:

#if ( ! $context.treasureMap.containsKey('gold'))
  #fail('no golden treasure here')
#end

Background

I am writing a maven site page. The velocity context is injected by maven and contains POM information. I want to test existence of some information from effective pom. When the information is not available, I want to fail.

Requirements

  • fail Velocity processing > fail site generation > fail maven build.
  • error message should lead to the place of failure so the site should be fixed
  • preferably no configuration (no extensions, just constructs/tools contained in plain Velocity)

Tried

  • Strict Reference Mode
    Unwanted configuration, do not want to fail on every occasion.
  • #evaluate('#end') aka syntax error
    (Chose #end as most descriptive to my intent) Basically what I want. Fails the processing and maven build but the error message does not lead back to failure location: ParseException: Encountered "#end" at line 1, column 1..
1 Answers

You need to make a method call which produce exception.See explanation:

The only place where one could run into trouble within Velocity is if there is a call to a method which throws an exception during runtime. For example, this VTL defines a String $foo and then attempts to call its substring() method on it would throw an IndexOutOfBoundsException:

 #set ($foo = "bar")

  #set ($bar = $foo.substring(0,10))

When the exception is thrown, the parser will stop processing and throw that exception up the stack tree where it can be caught in the method that caused the parser to execute. At that point, the exception can be handled gracefully.

Related