我正在编写一些服务器端代码,用于在将异常传递给客户端之前包装所有异常,因此所有面向客户端的方法都具有以下代码
try{
DoSomething();
} catch (ExceptionA e) {
throw new CustomException(AType, e);
} catch (ExceptionB e) {
throw new CustomException(BType, e);
} catch (Exception e) {
throw new CustomException(Unexpected, e);
}在每个方法中重复这一点似乎违反了DRY原则,我想知道重构它的最好方法是什么。例如,我在考虑一种包装器方法,例如:
private void wrapException(Exception e) {
if (e instanceof ExceptionA) {
throw new CustomException(AType, e);
}
etc...发布于 2012-11-13 19:13:44
看一看AspectJ软化异常。
还可以看看Guava的Throwables。
也有Lamboks偷偷的例外。
另一种选择是使用匿名对象实例,也称为闭包。
public abstract class Wrapper {
public void execute() {
try {
// do some boiler plate before
this.wrap();
// do some boiler plate after.
} catch (ExceptionA | ExceptionB ex) {
Type t = determineType(ex);
throw new CustomException(t, ex);
}
}
public void abstract wrap();
}现在,在您的代码中,您可以执行如下操作:
new Wrapper() {
public void wrap() {
DoSomething();
}
}.execute()发布于 2012-11-13 19:53:02
在Java7和更高版本中,这是可能的:
http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
上述文档中的复制-粘贴示例:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}发布于 2012-11-13 19:01:50
这是一种方法:
Exception caughtEx = null;
String extraInfo = null;
try{
DoSomething();
} catch (ExceptionA e) {
caughtEx = e;
extraInfo = AType;
} catch (ExceptionB e) {
caughtEx = e;
extraInfo = BType;
} catch (Exception e) { // catching Exception is usually a bad idea, just let it bubble up without catching...
caughtEx = e;
extraInfo = Unexpected;
}
if (caughtEx != null) throw new CustomException(extraInfo, caughtEx);https://stackoverflow.com/questions/13359490
复制相似问题