java的InvocationTargetException异常处理

前一段时间做项目的时候遇到了InvocationTargetException异常,这是个很奇怪的异常。原本通过反射去调用类里面的方法,该方法里面抛出的异常都是InvocationTargetException。这个异常的getMessage返回值为空,并没有覆写Exception的getMessage方法。所以如果要得到InvocationTargetException的这个异常信息。需要getTargetException得到这个目标异常信息。

比方说:

@Override

public String callService(String head, String body) {

// TODO Auto-generated method stub

BaseReturn baseReturn = new BaseReturn();

try {

checkInputParam(head, body);

return exec(head, body);

} catch (InvocationTargetException e) {

// TODO Auto-generated catch block

logger.error(e.getTargetException().getMessage());

baseReturn.setResultCode(Common.FAIL);// 设置错误结果码

baseReturn.setErrorInfo(e.getTargetException().getMessage());// 设置错误信息

e.printStackTrace();

} catch (Exception e) {

logger.error(e.getMessage());

baseReturn.setResultCode(Common.FAIL);// 设置错误结果码

baseReturn.setErrorInfo(e.getMessage());// 设置错误信息

e.printStackTrace();

}

return JSONObject.toJSONString(baseReturn);

}

以上代码这样写,可以兼容所有异常。如果抛出的是InvocationTargetException则直接捕获。如果是其他异常则让Exception 去捕获。

猜你喜欢

转载自747017186.iteye.com/blog/2339781