如何处理由ajax调用操作时struts2引发的异常?

时间:2013-03-21 10:03:48

标签: jquery ajax exception struts2

我使用jquery post方法在save中调用DepartmentAction方法,如果我保存了一个dup部门(db中不允许使用dup部门),save方法会抛出异常,但用户无法从页面获取有关它的任何信息,这是我的代码:

DepartmentAction类:

public class DepartmentAction extends ActionSupport{
  public String save() throws Exception
   {
    this.departmentService.save(this.dept);
    this.jsonResult = "success";
    return "save";
  }
 }

struts.xml中:

<package name="backstage-default" extends="ecs-default" namespace="/manager">
   <action name="dept_*" class="com.nader.action.DepartmentAction" method="{1}">
      <result name="save" type="json"><param name="root">jsonResult</param></result>
   </action>

 <global-results>
        <result name="error">/error.jsp</result>
    </global-results>

    <global-exception-mappings>
        <exception-mapping exception="java.lang.Exception" result="error"         />
    </global-exception-mappings>

test.jsp的:

     $.post('dept_save.do', 
                 {'dept.deptId':$("#dialog_dept_deptId").val(), 
                  'dept.deptName':$("#dialog_dept_deptName").val(),
                  'dept.manager':$("#dialog_dept_manager").val(),
                 },function(data, status, xhr){
                     alert(status);
                     if(status == 'success'){
                         alert('success:'+data);
                         $("#dialog-form").dialog("close");
                         getCountByAJAX();
                         getDeptByAJAX();
                     }else{
                         alert('error:'+data);
                     }
                  }
                 ,"json").fail(function(data, status, xhr)          {alert('fail:'+data);});

save抛出异常时,用户没有获得任何信息,没有错误,没有重定向,所以我该怎么办?我不想在Actions中编写try catch块,因为它使代码混乱太多了。还有其他方法吗?

提前致谢。

ps:我真的很抱歉,我只是粘贴了错误的javascript块,我更正了,现在当struts2抛出异常时执行fail处理程序,但我不知道是什么传递给浏览器的data是,我在Chrome工具中看到dept_save.do的响应,它包含所有的exceptionStack信息,这太多了,struts可以返回一些小信息或友情提示信息吗?

1 个答案:

答案 0 :(得分:1)

  

我不想在Actions中编写try catch块,因为它太过于让代码变得混乱。

这是一个无意义的论点。当您使用的框架组件可能抛出异常时,拥有来捕获那些,如果,您希望保持对程序流的控制,而不是让它在错误中突破

(你当然不必在那里捕获那个例外,而且 - 在程序流程的后期点也可以捕获异常。在程序结束之前,它们必须在所有地方被捕获。)