天天看点

异常处理的几种方式

1、手动式异常处理

Manager抛出异常:

throw new RuntimeException("不能删除该机构");

Action捕捉异常:

catch(Exception e) {

   ActionMessages msgs = new ActionMessages();

   //errors.detail=error{0},e.getMessage()实质等于"不能删除该机构"作为参数传入errors.detail

   ActionMessage msg = new ActionMessage("errors.detail",e.getMessage()); 

  msgs.add("detail",msg);

   this.saveErrors(request, msgs);

   return mapping.findForward("exception");

  }

struts-cfg.xml配置全局变量:

 <global-forwards>

  <forward name="exception" path="/common/exception.jsp"></forward>

 </global-forwards>

创建错误显示页面exceptioin.jsp显示异常信息:

<html:errors/>

2、struts自动处理

Manager仍然是抛出异常:

throw new RuntimeException("不能删除该机构");

Action把异常往上层抛:

throws Exception

struts-cfg.xml配置异常标签:

     <exception

      key="errors.detail"

      type="java.lang.RuntimeException"

      scope="request"

      path="/common/exception.jsp">

     </exception>

3、创建一个统一的异常类处理全部的异常,用一个key指向异常的国际化信息:

throw--><exception>-->SystemException-->SystemExceptionHandler

Manager仍然是抛出异常:

 throw new SystemException("不能删除该机构","exception.org.del");

struts-cfg.xml配置异常标签:

 <global-exceptions>

     <exception

      key="errors.detail"

      type="com.oa.manager.SystemException"

      handler="com.oa.manager.SystemExceptionHandler"

      scope="request"

      path="/common/exception.jsp">

     </exception>

   </global-exceptions> 

SystemException类:

public class SystemException extends RuntimeException {

private String key;

//调用父类的构造方法

public SystemException() {

super();

}

public SystemException(String message, Throwable cause) {

super(message, cause);

}

public SystemException(String message) {

super(message);

}

public SystemException(Throwable cause) {

super(cause);

}

//自定义构造方法

public SystemException(String msg, String key) {

super(msg);

this.key = key;

}

public String getKey() {

return key;

}

}

SystemExceptionHandler类:

public class SystemExceptionHandler extends ExceptionHandler {

@Override

public ActionForward execute(Exception ex, ExceptionConfig ae,

ActionMapping mapping, ActionForm formInstance,

HttpServletRequest request, HttpServletResponse response)

throws ServletException {

//从struts配置文件中获取forward

ActionForward forward = null;

if(ae.getPath() != null) {

forward = new ActionForward(ae.getPath());

}else{

forward = new ActionForward(mapping.getInputForward());

}

//从需要处理的异常对象中获取异常信息

ActionMessage msg = null;

if(ex instanceof SystemException) {

SystemException se = (SystemException)ex;

if(se.getKey() != null) {

msg = new ActionMessage(se.getKey(),se.getMessage());

}else{

msg = new ActionMessage(ae.getKey(), se.getMessage());

}

this.storeException(request, "detail", msg, forward, ae.getScope());

return forward;

}

return super.execute(ex, ae, mapping, formInstance, request, response);

}

}

 MessageResources.properties:

exception.org.del=Can't delete the org with suborg