InvocationHandler 的异常处理


最近发现个问题, 客户端请求返回的错误码不对, 仔细看了代码,程序里面是通过异常捕获来
获得错误码的。 被调用的业务方法抛出异常,结果在实际捕获的时候,不是原来的异常了。

怎么回事呢? 在仔细一下,原来是 log proxy 实现的不好导致的问题。

注意下面的代码中的 catch部分, 只有这样处理,才能保证会抛出被调用的方法抛出的异常,
因为被调用的方法不在throws列表中,这时会被转换成另一个异常,所以这里需要捕获
这样的情况并抛出原有的异常。

参考了Spring的代码才发现是这样的,呵呵

public class LogProxyHandler implements java.lang.reflect.InvocationHandler {

    private Object    obj;
    private Log        log    = LogFactory.getLog(getClass());

    public LogProxyHandler(Object obj) {
        this.obj = obj;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            long start = System.currentTimeMillis();
            Object r = method.invoke(obj, args);
            long end = System.currentTimeMillis();
            long time = end - start;
            if (time < 10) {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("ShortAction:%s.%s takes [%d]ms.", obj.getClass().getSimpleName(), method.getName(), time));
                }
            } else if (time < 200) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("MiddleAction:%s.%s takes [%d]ms.", obj.getClass().getSimpleName(), method.getName(), time));
                }
            } else if (time < 500) {
                if (log.isWarnEnabled()) {
                    log.warn(String.format("LongAction:%s.%s takes [%d]ms.", obj.getClass().getSimpleName(), method.getName(), time));
                }
            } else {
                if (log.isErrorEnabled()) {
                    log.error(String.format("LongestAction:%s.%s takes [%d]ms.", obj.getClass().getSimpleName(), method.getName(), time));
                }
            }       
            return r;
        } catch (InvocationTargetException ex) {
            throw ex.getTargetException();
        }
    }
}


测试代码

public interface TestInterface {
    public void test();
}

public class TestLogHandlerException implements TestInterface{
    public static void main(String[] args) throws Throwable{
        TestLogHandlerException t = new TestLogHandlerException();
       
        TestInterface nt;
        nt = (TestInterface) Proxy.newProxyInstance(TestInterface.class.getClassLoader(), new Class[] { TestInterface.class }, new LogProxyHandler(t));
        nt.test();
    }
   
    public void test() {
        System.out.println("kaka");
        throw new IllegalStateException("eehe");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值