Recent Bloggers

Jamie Sammons

Staff
10 Publications
23 octobre 2017

Jan Verweij

Staff
2 Publications
23 octobre 2017

Yasuyuki Takeo

Staff
2 Publications
18 octobre 2017

David H Nebinger

63 Publications
14 octobre 2017

Anderson Perrelli

Staff
1 Publications
9 octobre 2017

Kyle Joseph Stiemann

Staff
11 Publications
6 octobre 2017

Petteri Karttunen

Staff
2 Publications
5 octobre 2017

James Hinkey

Staff
8 Publications
5 octobre 2017

Sushil Patidar

10 Publications
4 octobre 2017

Bryan Cheung

Staff
37 Publications
4 octobre 2017

Exception Handling in Velocity Templates

General Blogs 28 avril 2014 Par Parth Ghaswala

Hi Guys,

I am using Liferay 6.1.

Recently I faced an issue, which kept me wondering for getting tricks to handle exceptions in velocity file.

Ideally we can't do any exception handling directly to .vm files.

But here is the trick to get it done:

Using Service-Pre-Action hook, we can achieve this.

Step 1 : Create ServicePreAction hook

public class MyServicePreAction extends Action {

       public void run(HttpServletRequest request, HttpServletResponse response)
            throws ActionException

      {

                        Map<String, Object> vmVariables = new HashMap<String, Object>();
                       vmVariables.put("customVelocityVariable", new MyServicePreAction());

                       request.setAttribute(WebKeys.VM_VARIABLES, vmVariables);

      }

    public String myFunctionCalledFromVM (String param1, int param2, int param3)

    {

              try{

                     //Business logic for which exception handling needed to be done at velocity files, is                                     // to be written here.

                   }

             catch(Exception e)

              {

              }

       }

}

Step 2 Call ServicePreAction Fuction to Velocity File:

Object of MyServicePreAction gets registered to Velocity Variables pool with name of customVelocityVariable, as coded above.

Now user can call function myFunctionCalledFromVM (........) with customVelocityVariable in .vm files as below:

$customVelocityVariable.myFunctionCalledFromVM("param1",2,3);

If any exception occurs at this call, that gets handled in Service PreAction hook. And finally we got exception handling done for our velocity files bussiness logics.

Here what ever logic you are supposed to put at .vm files, put that to this myFunctionCalledFromVM().

Hope this helps you.

 

Affichage de 1 résultat(s).