7

How to throw an user-defined exception from Velocity Template Script (VTL) ?

From my velocity script, i need to throw an exception based on a condition, so that the caller can catch the exception and present an useful error messages to the end user.

For Example.

#if($passwordfield1 != $passwordfield2)
throw an exception here
#elseif($passwordfield1 == $passwordfield2)
do something
#end

In the above example, if passwordfield1 and passwordfield2 is not matching,an appropriate exception should be thrown and that needs to be propagated to the end-user.

Is there any way to achieve this from velocity script? If not, please suggest an alternate approach.

anuu_online
  • 374
  • 1
  • 3
  • 14

1 Answers1

5
context.put("exceptionThrower", new ExceptionThrower());

public class ExceptionThrower {
    public void throwUserDefined() {
        throw new UserDefinedException();
    }
}

#if ($whatever) 
$exceptionThrower.throwUserDefined()
#else
blah blah
#end
Nathan Bubna
  • 6,823
  • 2
  • 35
  • 36
  • Could you give more details please? In my template the java code was just output directly. Does it need to be escaped somehow? – RonanOD May 29 '15 at 17:48
  • 1
    This is three separate pieces of code. The 2nd is a standalone Java class. The 1st is instantiation of that class and insertion into your Velocity context. The 3rd is how you would use such a tool in the template. Do not just insert this all into your template. Only the 3rd section is VTL. – Nathan Bubna Jun 01 '15 at 16:55