异常处理的几种方式

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类:

 

SystemExceptionHandler类:

 

 MessageResources.properties:

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

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值