如何解决上面的问题呢?我是这样做的:JDK异常或自定义异常+异常拦截器
struts2拦截器的作用在网上有很多资料,在此不再赘述,我的异常拦截器原理如下图所示:
首先我的action类、service类和dao类如果有必要捕获异常,我都会try...catch,catch块内不记录log,通常是抛出一个新异常,并且注明错误信息:
//action层执行数据添加操作 public String save(){ try{ //调用service的save方法 service.save(obj); }catch(Exception e){ //你问我为什么抛出Runtime异常?因为我懒得在方法后写throws xx throw new RuntimeException("添加数据时发生错误!",e); } return "success"; } |
然后在异常拦截器对异常进行处理,看下面的代码:
public String intercept(ActionInvocation actioninvocation) { String result = null; // Action的返回值 try { // 运行被拦截的Action,期间如果发生异常会被catch住 result = actioninvocation.invoke(); return result; } catch (Exception e) { /** * 处理异常 */ String errorMsg = "未知错误!"; //通过instanceof判断到底是什么异常类型 if (e instanceof BaseException) { BaseException be = (BaseException) e; be.printStackTrace(); //开发时打印异常信息,方便调试 if(be.getMessage()!=null||Constants.BLANK.equals(be.getMessage().trim())){ //获得错误信息 errorMsg = be.getMessage().trim(); } } else if(e instanceof RuntimeException){ //未知的运行时异常 RuntimeException re = (RuntimeException)e; re.printStackTrace(); } else{ //未知的严重异常 e.printStackTrace(); } //把自定义错误信息 HttpServletRequest request = (HttpServletRequest) actioninvocation .getInvocationContext().get(StrutsStatics.HTTP_REQUEST); /** * 发送错误消息到页面 */ request.setAttribute("errorMsg", errorMsg); /** * log4j记录日志 */ Log log = LogFactory .getLog(actioninvocation.getAction().getClass()); if (e.getCause() != null){ log.error(errorMsg, e); }else{ log.error(errorMsg, e); } return "error"; }// ...end of catch } |