2017-03-28 19 views
0

我在我的服务提出了以下插入/更新方法:如何在类似的方法中消除重复的try-catch代码?

@Override 
public void insertEntity(Entity entity) { 

    try {   
    entityDao.insert(entityMapper.entityToEntityDO(entity)); 

    } catch (DataIntegrityViolationException ex){ 

    if(ex.getCause() instanceof SQLIntegrityConstraintViolationException) { 
     SQLIntegrityConstraintViolationException violationEx = (SQLIntegrityConstraintViolationException) ex.getCause(); 
     if(violationEx.getErrorCode() == 1048 && "23000".equals(violationEx.getSQLState())) { 
     throw new FieldCannotBeNullException(violationEx.getMessage()); 
     } 
    } 

    throw ex; 
    } 
} 

@Override 
public void updateEntity(Entity entity) { 

    try {   
    entityDao.update(entityMapper.entityToEntityDO(entity)); 

    } catch (DataIntegrityViolationException ex){ 

    if(ex.getCause() instanceof SQLIntegrityConstraintViolationException) { 
     SQLIntegrityConstraintViolationException violationEx = (SQLIntegrityConstraintViolationException) ex.getCause(); 
     if(violationEx.getErrorCode() == 1048 && "23000".equals(violationEx.getSQLState())) { 
     throw new FieldCannotBeNullException(violationEx.getMessage()); 
     } 
    } 

    throw ex; 
    } 
} 

正如你所看到的,insertEntity实际逻辑和updateEntity是非常简单的。为了抛出自定义Exception,我做了一些数据库错误代码检查。由于这两种方法都需要这种检查,所以这两种方法中的代码都是重复的,这显然是一种代码异味。

如何消除这种代码重复?

+0

望着'@ Override'注解:就是Java 8中,什么是超类或实现的接口具有'updateEntity'和'insertEntity'-方法? –

+0

我只是把catch块中的代码放到一个单独的方法中。 –

+0

您可能会考虑将异常作为控制流量的一种方式。我认为你所做的不仅仅是检查空列 - 所以调用这些方法的代码有很多异常处理要做。这在Java中是惯用的,但不是特别易读或者高效...... –

回答

2

将通用catch-block提取为引发DataIntegrityViolationException的方法。

0

您可以将catch块内的代码放入单独的方法中。

或者,您可以捕获Exception,并编写处理方法来处理异常,如果将来您希望在那里处理多个异常。

0

你可以这样创建接口:

public interface ConsumerWithException<T, V extends Exception> { 
    /** 
    * Performs this operation on the given argument. 
    * 
    * @param t the input argument 
    */ 
    void accept(T t) throws V; 

} 

使用它的私有方法,如:

private void action(ConsumerWithException<Entity, DataIntegrityViolationException> doAction, Entity entity){ 
    try { 
     doAction.accept(entity); 
    } catch (DataIntegrityViolationException ex){ 

     if(ex.getCause() instanceof SQLIntegrityConstraintViolationException) { 
      SQLIntegrityConstraintViolationException violationEx = (SQLIntegrityConstraintViolationException) ex.getCause(); 
      if(violationEx.getErrorCode() == 1048 && "23000".equals(violationEx.getSQLState())) { 
       throw new FieldCannotBeNullException(violationEx.getMessage()); 
      } 
     } 

     throw ex; 
    } 
}