HTTP网络连接相关知识整理(六):分发处理根异常

在java中获取到一个exception后有时需要获取该异常的根异常,实现方法有多重,本文介绍两种方式:一种是逐一判断该异常属于哪一个异常的实例,另一个是遍历找到最终抛出异常的类型。


1、判断异常实例类型

java中可以使用instanceof判断该对象是否是某一个类的实例,通过该方法可以判断异常的类型并调用相应的处理方法。

demo如下,在Java web中使用instanceof判断异常类型并调用不同的方法进行处理

[java]  view plain  copy
 print ?
  1. package com.landsem.update.base.exception.handler;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.apache.log4j.Logger;  
  7. import org.springframework.dao.DataIntegrityViolationException;  
  8. import org.springframework.web.servlet.HandlerExceptionResolver;  
  9. import org.springframework.web.servlet.ModelAndView;  
  10.   
  11. import com.landsem.update.base.exception.ActionUnSupportException;  
  12.   
  13. public class ExceptionDispatcher implements HandlerExceptionResolver {  
  14.     protected static Logger logger = Logger.getLogger(ExceptionDispatcher.class);  
  15.   
  16.     @Override  
  17.     public ModelAndView resolveException(HttpServletRequest arg0,  
  18.             HttpServletResponse arg1, Object arg2, Exception arg3) {  
  19.   
  20.         //action unSupport exception.自定义的异常  
  21.         if (arg3 instanceof ActionUnSupportException) {  
  22.             logger.error("ActionUnSupportException exception.");  
  23.             arg3.printStackTrace();  
  24.         }  
  25.         //DataIntegrityViolationException exception.数据库抛出的异常  
  26.         else if (arg3 instanceof DataIntegrityViolationException) {  
  27.             logger.error("DataIntegrityViolationException");  
  28.             arg3.printStackTrace();  
  29.         }  
  30.         //base exception.根异常  
  31.         else if (arg3 instanceof Exception) {  
  32.             logger.error("unknown exception.");  
  33.             arg3.printStackTrace();  
  34.         }  
  35.         return null;  
  36.     }  
  37.   
  38. }  

2、遍历获取根异常并通过反射机制调用处理方法

通过判断异常的getCause是否为空判断是否为最终的异常抛出类。

     参考如下demo,java web(配置略,如需查看配置方法请参考http://blog.csdn.net/smilefyx/article/details/49420555)中实现异常捕获并根据最终的异常类型通过反射机制调用异常类型+Handler的类的handlerException方法进行处理进行异常处理。

[java]  view plain  copy
 print ?
  1. package com.landsem.update.base.exception.handler;  
  2.   
  3. import java.lang.reflect.Method;  
  4.   
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7.   
  8. import org.apache.log4j.Logger;  
  9. import org.springframework.web.servlet.HandlerExceptionResolver;  
  10. import org.springframework.web.servlet.ModelAndView;  
  11.   
  12. public class ExceptionDispatcher implements HandlerExceptionResolver {  
  13.     protected static Logger logger = Logger  
  14.             .getLogger(ExceptionDispatcher.class);  
  15.   
  16.     @Override  
  17.     public ModelAndView resolveException(HttpServletRequest arg0,  
  18.             HttpServletResponse arg1, Object arg2, Exception arg3) {  
  19.         //  
  20.         if (null != arg3) {  
  21.             Throwable tb = findRootExceptionThrowable(arg3);  
  22.             if (null != tb) {  
  23.                 String basePackageName = this.getClass().getPackage().getName();  
  24.                 String exceptionBaseName = tb.getClass().getName();  
  25.                 String handlerClassName = new StringBuffer()  
  26.                         .append(basePackageName)  
  27.                         .append(exceptionBaseName.substring(exceptionBaseName  
  28.                                 .lastIndexOf("."))).append("Handler").toString();  
  29.                 logger.info(handlerClassName);  
  30.                 try {  
  31.                     Class<?> cls = Class.forName(handlerClassName);  
  32.                     if (null != cls) {  
  33.                         Method m = cls.getDeclaredMethod("handlerException",  
  34.                                 new Class[] { HttpServletRequest.class,  
  35.                                         HttpServletResponse.class, Object.class,  
  36.                                         Throwable.class });  
  37.                         if (null != m) {  
  38.                             return (ModelAndView) m.invoke(cls.newInstance(), arg0,  
  39.                                     arg1, arg2, tb);  
  40.                         }  
  41.                     }  
  42.                 } catch (Exception e) {  
  43.                     // TODO Auto-generated catch block  
  44.                     e.printStackTrace();  
  45.                 }  
  46.             }  
  47.         }  
  48.         return null;  
  49.     }  
  50.   
  51.     /** 
  52.      * find root exception throwable. 
  53.      *  
  54.      * @param e 
  55.      * @return 
  56.      */  
  57.     protected Throwable findRootExceptionThrowable(Exception e) {  
  58.         /* 
  59.          * Throwable tmp = e.getCause(); while (null != tmp && 
  60.          * !(tmp.getClass().getName().equals(tmp.getCause().getClass() 
  61.          * .getName()))) { tmp = tmp.getCause(); } return tmp; 
  62.          */  
  63.         Throwable rootCause = e;  
  64.   
  65.         while (rootCause.getCause() != null) {  
  66.             rootCause = rootCause.getCause();  
  67.         }  
  68.         return rootCause;  
  69.     }  
  70.   
  71. }  

异常处理类实现如下接口方便通过反射调用到处理方法:

[java]  view plain  copy
 print ?
  1. package com.landsem.update.base.exception.handler;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.springframework.web.servlet.ModelAndView;  
  7.   
  8. public interface IExceptionHandler {  
  9.     public ModelAndView handlerException(HttpServletRequest request,  
  10.             HttpServletResponse response, Object arg,Throwable tb);  
  11. }  

如下为一个简单的ParamsFormatErrorExceptionHandler实现,当抛出自定义异常ParamsFormatErrorException时被反射调用。

[java]  view plain  copy
 print ?
  1. package com.landsem.update.base.exception.handler;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.apache.log4j.Logger;  
  7. import org.springframework.web.servlet.ModelAndView;  
  8.   
  9. public class ParamsFormatErrorExceptionHandler implements IExceptionHandler{  
  10.     protected static Logger logger = Logger  
  11.             .getLogger(ExceptionDispatcher.class);    
  12.   
  13.     @Override  
  14.     public ModelAndView handlerException(HttpServletRequest request,  
  15.             HttpServletResponse response, Object arg, Throwable tb) {  
  16.         logger.error("request format error!");  
  17.         return null;  
  18.     }  
  19.   
  20. }

转载原文出处http://blog.csdn.net/smilefyx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值