繁体   English   中英

Java异常工厂用于更高级别的异常

[英]Java exception factory for higher level exceptions

我正在寻找创建异常工厂

我有一个连接到不同数据存储的服务,这些数据存储引发许多异常。 我不想将这些异常返回给服务的用户,而是返回更高级别的异常,例如storeServiceTransientReadException

当连接到数据存储时,我将使用try,catch模式。 例如对于Cassandra连接:

public ResultSet safeExecute(Statement statement) throws StoreServiceException {
    try {
        return session.execute(statement);
    } 
    catch(QueryExecutionException ex){
        log.error(ex);
        StoreServiceException storeException = StoreServiceExceptionFactory.getTransientException(ex);
        throw storeException;
    }

在cassandra示例中,我希望工厂根据该异常是ReadFailureException,ReadTimeoutException,WriteFailureException还是WriteTimeoutException创建一个读写storeServiceException异常。

对于其他数据存储,我想遵循相同的模式,那么该服务的用户将只需要担心服务错误,而不必担心特定的数据存储错误。

对于工厂,我一直在思考(伪):

public class ExceptionsFactory {

public StoreServiceTransientException getTransientException(Exception ex){

    if  ReadException
        return  StoreServiceTransientException("read exception ")


    if WriteException 
        return  StoreServiceTransientException("write exception ")

}

public StoreServiceNonTransientException getTransientNonException(Exception ex){

    if  ReadException
        return  StoreServiceNonTransientException("read exception ")


    if WriteException 
        return  StoreServiceNonTransientException("write exception ")


}

但是我找不到许多令我担心的在线示例。 这真是个坏主意吗? 我应该只是有很多更具体的catch块,这些块返回我想要的storeServiceException?

这真是个坏主意吗? 我认为是的。 这是一个坏主意。 使用Exception的昂贵部分是填充堆栈跟踪。 如果您预先创建并保存抛出的Exception ,则堆栈跟踪将毫无意义(或至少具有大大降低的价值)。 您当前未记录堆栈跟踪,因此我也将进行更改

log.error(ex);

log.error("Caught exception: " + ex.getMessage(), ex);

并且类似地实例化具有潜在原因的异常-

throw new storeServiceException("Exception in storage.", ex);

并且该名称应遵循正常的命名约定。 Java类名以大写字母开头-您的名字看起来像一个变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM