error-handlingstruts2resourcebundlestruts1

Migration error handling to Struts2


To display errors we need message keys which contains the error messages. I create a new resource bundle named ApplicationError.properties which contain this property:

app.error=Error: {0}

I try to change this class from struts1 to struts2, but I have a problem with error handling.I have not found the equivalent in struts2

   public class MyAction extends Action{

    public ActionForward execute(ActionMapping actionMapping,
                    ActionForm actionForm,
                    HttpServletRequest request,
                    HttpServletResponse response)
                 throws Exception{

    ActionErrors actionErrors = new ActionErrors();
    ActionMessage message = new ActionMessage("app.error","Not Found Exception");


    try{
    //some code

    }catch(NotFoundException e){
        actionErrors.add(ActionErrors.GLOBAL_MESSAGE, message);
        saveErrors(request, actionErrors);
        return getErrorActionForward(actionMapping);

    }
    return getActionForward(actionMapping);
}

Can you help me with this?


Solution

  • Checkout ActionSupport class that your action class to extend. Then use its methods to add errors.

    This class also implements a TextProvider, so you can get localized messages from the resources.

    /** Add an Action-level error message to this Action. */
    void  addActionError(String anErrorMessage)
    
    /** Add an Action-level message to this Action. */
    void  addActionMessage(String aMessage)