Search code examples
exceptionvelocityuser-definedvtl

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


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.


Solution

  • context.put("exceptionThrower", new ExceptionThrower());
    
    public class ExceptionThrower {
        public void throwUserDefined() {
            throw new UserDefinedException();
        }
    }
    
    #if ($whatever) 
    $exceptionThrower.throwUserDefined()
    #else
    blah blah
    #end