纳税服务系统三(优化处理)【异常处理、抽取BaseAction】

前言

本博文主要讲解在项目中异常是怎么处理的。一般我们都不会直接把后台异常信息返回给用户,用户是看不懂的。让用户看见一大串的错误代码,这是不合理的。因此我们需要对报错进行处理。

我们在开发的时候是使用层次来进行开发的。因此有三个层次:

① Action层可能出现解析请求参数、返回结果有问题;

② Service 层则可能出现请求中要做的业务操作出现问题;出现了问题要根据实际情况判断是否会影响本次操作结果,action中要根据异常信息进行判断然后确定是否操作成功;

③ dao层也可能出现在操作数据库时出现错误;而此种错误一般都是致命的会影响操作结果。

因此;在3个层次中至少要有两种类型的异常信息来标识。

异常类的定义应该放在core核心模块的exception包下的。

640?wx_fmt=png
这里写图片描述

自定义异常类

总的系统异常类

/**** * 这是我们自定义的总系统异常类 * * */public class SysException extends Exception {    //用来记录错误的信息!    private String errorMsg;    public String getErrorMsg() {        return errorMsg;    }    public void setErrorMsg(String errorMsg) {        this.errorMsg = errorMsg;    }    public SysException() {    }    public SysException(String message) {        super(message);        this.errorMsg= message;    }    public SysException(String message, Throwable cause) {        super(message, cause);        this.errorMsg= message;    }    public SysException(Throwable cause) {        super(cause);    }}
public class SysException extends Exception {

   //用来记录错误的信息!
   private String errorMsg;

   public String getErrorMsg() {
       return errorMsg;
   }
   public void setErrorMsg(String errorMsg) {
       this.errorMsg = errorMsg;
   }
   public SysException() {
   }

   public SysException(String message) {
       super(message);
       this.errorMsg= message;
   }

   public SysException(String message, Throwable cause) {
       super(message, cause);
       this.errorMsg= message;
   }

   public SysException(Throwable cause) {
       super(cause);
   }
}

Action异常类

继承着我们自定义的总系统异常类/** * Action的异常类 * */public class ActionException extends SysException {    public ActionException() {        super("请求操作失败了!");    }    public ActionException(String message) {        super(message);    }}
/**
* Action的异常类
* */

public class ActionException extends SysException {

   public ActionException() {

       super("请求操作失败了!");
   }

   public ActionException(String message) {
       super(message);
   }
}

Service异常类

/** * Created by ozc on 2017/5/26. */public class ServiceException extends SysException {    public ServiceException() {        super("操作业务失败了!");    }    public ServiceException(String message) {        super(message);    }}
public class ServiceException extends SysException {
   public ServiceException() {
       super("操作业务失败了!");

   }

   public ServiceException(String message) {
       super(message);
   }
}

全局异常映射

我们使用的是Struts2框架,想要报错的信息不直接给用户看见。就在Struts总配置文件中配置对应的映射。

    <!-- 配置全局结果及异常映射 -->    <package name="base-default" extends="struts-default">        <!-- 全局返回结果 -->        <global-results>            <!--这是我们自定义异常的错误-->            <result name="sysError">/WEB-INF/jsp/error.jsp</result>            <!--这是找不着映射路径的错误-->            <result name="input">/WEB-INF/jsp/error.jsp</result>        </global-results>        <!-- 全局异常映射 -->        <global-exception-mappings>            <exception-mapping result="sysError" exception="zhongfucheng.core.exception.SysException"></exception-mapping>            <exception-mapping result="input" exception="java.lang.Exception"></exception-mapping>        </global-exception-mappings>    </package>
   <package name="base-default" extends="struts-default">
       <!-- 全局返回结果 -->
       <global-results>

           <!--这是我们自定义异常的错误-->
           <result name="sysError">/WEB-INF/jsp/error.jsp</result>
           <!--这是找不着映射路径的错误-->
           <result name="input">/WEB-INF/jsp/error.jsp</result>
       </global-results>

       <!-- 全局异常映射 -->
       <global-exception-mappings>
           <exception-mapping result="sysError" exception="zhongfucheng.core.exception.SysException"></exception-mapping>
           <exception-mapping result="input" exception="java.lang.Exception"></exception-mapping>
       </global-exception-mappings>
   </package>

应用

在子模块中,只要继承着我配置异常信息的package就行了。

640?wx_fmt=png
这里写图片描述

Serive层抛出异常:

    @Override    public List<User> findObjects() throws ServiceException {        try {            int i = 1 / 0;        } catch (Exception e) {            throw new ServiceException(e.getMessage());        }        return userDaoImpl.findObjects();    }
   public List<User> findObjects() throws ServiceException {

       try {
           int i = 1 / 0;
       } catch (Exception e) {
           throw new ServiceException(e.getMessage());
       }
       return userDaoImpl.findObjects();

   }

Action层把它catch住,并抛出Action异常:

    //抛出Action异常    public String listUI() throws ActionException {        try {            userList = userServiceImpl.findObjects();        } catch (ServiceException e) {            throw new ActionException("请求操作失败!!!" + e.getMessage());        }        return "listUI";    }
   public String listUI() throws ActionException {
       try {
           userList = userServiceImpl.findObjects();
       } catch (ServiceException e) {
           throw new ActionException("请求操作失败!!!" + e.getMessage());
       }
       return "listUI";
   }

即使Action中出现了ActionExcpetion以外的异常,我们在Struts配置文件中已经配置了Exception了。还是可以将它捕获得到

  <body>      <img src="<%=request.getContextPath() %>/images/common/error.jpg">    <br>    <s:if test="exception.errorMsg != '' && exception.errorMsg != null">        <s:property value="exception.errorMsg"/>    </s:if>    <s:else>        操作失败!<s:property value="exception.message"/>    </s:else>  </body>
     <img src="<%=request.getContextPath() %>/images/common/error.jpg">
   <br>
   <s:if test="exception.errorMsg != '' && exception.errorMsg != null">
       <s:property value="exception.errorMsg"/>
   </s:if>
   <s:else>
       操作失败!<s:property value="exception.message"/>
   </s:else>
 </body>

效果:

640?wx_fmt=png
这里写图片描述

抽取BaseAction

我们在用Action的时候,未免都会存在一些功能的属性。例如:在listUI,我们要获取多个用户的时候,需要有selectedRow这么一个属性。在其他的子模块也应该要有这个样属性。所以我们可以抽取出来--->形成一个BaseAction。其他的Action只要继承着BaseAction就有相对应的属性了。

public class BaseAction extends ActionSupport {    public  String[] selectedRow;    public String[] getSelectedRow() {        return selectedRow;    }    public void setSelectedRow(String[] selectedRow) {        this.selectedRow = selectedRow;    }}class BaseAction extends ActionSupport {

   public  String[] selectedRow;

   public String[] getSelectedRow() {
       return selectedRow;
   }

   public void setSelectedRow(String[] selectedRow) {
       this.selectedRow = selectedRow;
   }


}

制定返回类型StrutsResultSupport

在有特殊情况时;如果没有异常信息,但是有错误并且有错误信息等内容;此时也需要进行友好的错误处理的话,那么可以借助StrutsResultSupport 返回结果类型来实现特定处理。

此种方式先需要继承StrutsResultSupport ,然后可以在子类中获取本次请求的相关信息,再根据相关信息进行结果处理

import com.opensymphony.xwork2.ActionInvocation;import org.apache.struts2.ServletActionContext;import org.apache.struts2.dispatcher.StrutsResultSupport;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class SysResultAction extends StrutsResultSupport {    @Override    protected void doExecute(String arg0, ActionInvocation invocation) throws Exception {        HttpServletRequest request = ServletActionContext.getRequest();        HttpServletResponse response = ServletActionContext.getResponse();        BaseAction action = (BaseAction)invocation.getAction();         //do something        System.out.println("进入了 SysResultAction ...");    }}
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SysResultAction extends StrutsResultSupport {

   @Override
   protected void doExecute(String arg0, ActionInvocation invocation) throws Exception {
       HttpServletRequest request = ServletActionContext.getRequest();
       HttpServletResponse response = ServletActionContext.getResponse();
       BaseAction action = (BaseAction)invocation.getAction();


       //do something
       System.out.println("进入了 SysResultAction ...");
   }

}

配置:

    <!-- 配置全局结果及异常映射 -->    <package name="base-default" extends="struts-default">        <!-- 返回结果类型 -->        <result-types>            <result-type name="error" class="zhongfucheng.action.SysResultAction"></result-type>        </result-types>        <!-- 全局返回结果 -->        <global-results>            <result name="error" type="error">/WEB-INF/jsp/error.jsp</result>            <result name="sysError">/WEB-INF/jsp/error.jsp</result>            <result name="input">/WEB-INF/jsp/error.jsp</result>        </global-results>        <!-- 全局异常映射 -->        <global-exception-mappings>            <exception-mapping result="sysError" exception="zhongfucheng.action.SysResultAction"></exception-mapping>            <exception-mapping result="input" exception="java.lang.Exception"></exception-mapping>        </global-exception-mappings>    </package>
   <package name="base-default" extends="struts-default">
       <!-- 返回结果类型 -->
       <result-types>
           <result-type name="error" class="zhongfucheng.action.SysResultAction"></result-type>
       </result-types>
       <!-- 全局返回结果 -->
       <global-results>
           <result name="error" type="error">/WEB-INF/jsp/error.jsp</result>
           <result name="sysError">/WEB-INF/jsp/error.jsp</result>
           <result name="input">/WEB-INF/jsp/error.jsp</result>
       </global-results>
       <!-- 全局异常映射 -->
       <global-exception-mappings>

           <exception-mapping result="sysError" exception="zhongfucheng.action.SysResultAction"></exception-mapping>
           <exception-mapping result="input" exception="java.lang.Exception"></exception-mapping>
       </global-exception-mappings>
   </package>

总结

如果文章有错的地方欢迎指正,大家互相交流。习惯在微信看技术文章,想要获取更多的Java资源的同学,可以关注微信公众号:Java3y


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值