java 反射方法异常处理 InvocationTargetException

项目使用了反射进行方法调用,被调用的方法内抛出自己封装的Exception,外部无法捕捉到自定义Exception,捕捉到InvocationTargetException。

java.lang.ClassCastException: java.lang.reflect.InvocationTargetException

cannot be cast to com.test.test.exception.BaseException

public <T> BaseResponse handleRequest(T param, Integer type) {
   BaseResponse br = null;
   WHMethod methodEnum = WHMethod.getByMethod(type);
   String responseMsg = null;
   String responseCode = null;

   if (methodEnum == null) {
      logger.error("未获取到需要执行的方法");
      throw new BaseException(BackCode.GET_METHOD_NULL_ERROR);
   }
   try {
      String method = methodEnum.getMethod();
      Method m = this.getClass().getMethod(method, new Class[] { methodEnum.getRequestType() });
      br = (BaseResponse) m.invoke(whHouseStrategy, param);
   } catch (Exception e) {
      Throwable throwable = e.getCause();
      if (throwable instanceof BaseException) {
         responseMsg = ((BaseException) throwable).getDescription();
         responseCode = ((BaseException) throwable).getErrorcode();
         throw new BaseException(BackCode.NET_ERROR.getIndex(), responseMsg);
      }

      logger.error("【handleRequest公共请求方法】调用接口错误,详细信息:" + ExceptionUtils.getStackTrace(e));
      throw new BaseException(BackCode.NET_ERROR.getIndex(), methodEnum.getErrorMsg());
   }

   return br;
}

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0