YoK*_*YoK 9 java exception-handling
目前我正在使用库,它可以抛出很多不同的异常(每个方法调用8-10个),并且大多数必须处理,更糟的是每个方法(在任何时候)都可以抛出AuthenticationExpiredException
,我必须重新尝试进行身份验证.例如:
try {
xStream = xSet.createXStream(id, binding, mimeType); //Method call
} catch (AuthenticationExpiredException authenticationExpiredException) {
try {
this.authenticate(); // re-authenticate
xStream = xSet.createXStream(id, binding, mimeType); //Method call again
} catch (XAMException xamException) {
throw new ConnectorException(
"Error occurred during creating new Blob after attempting to re-authenticate",
xamException);
}
} catch (XSystemCorruptException xSystemCorruptException) {
this.entities.clear();
this.closeConnection();
throw new ConnectorException("XSystem was corrupt and connection was closed",
xSystemCorruptException);
} catch (XSetCorruptException xSetCorruptException) {
this.closeEntity(entity);
throw new ConnectorException("XSet for entity: " + entity.getXuid()
+ " was currupt and removed", xSetCorruptException);
} catch (XAMException xamException) {
throw new ConnectorException(
"Error occurred during creating new Blob.", xamException);
}
Run Code Online (Sandbox Code Playgroud)
这是异常处理的最小例子之一.这里的主要问题是,有没有办法减少处理异常的代码量,并使逻辑更清晰?
感谢您的反馈意见.我决定通过包装每个方法并分别处理它来为这个库创建单独的包装器.为了支持不同的处理方法,我为包装器创建了接口,然后使用我的自定义包装器实现它,如下所示:
public interface XAMLibraryWrapper{
// Methods
}
/**
* Will attempt to recover before throwing RuntimeException
*/
public class RecoveringXAMLibraryWrapper implements XAMLibraryWrapper{
// Implementation
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
600 次 |
最近记录: |