Java - find the first cause of an exception

后端 未结 10 1050
渐次进展
渐次进展 2020-12-09 01:50

I need to check if an exception is caused by some database problem. I receive an Exception and check if its cause contains the \"ORA\" string and return that (something like

10条回答
  •  甜味超标
    2020-12-09 02:18

    Probably a bit overkill for your usage but I think it is cleaner (and reusable)

    interface ThrowablePredicate {
        boolean accept(Throwable t);
    }
    
    public OracleErrorThrowablePredicate implements ThrowablePredicate {
        private static final ORA_ERR = "ORA";
    
        public boolean accept(Throwable t) {
            return t.toString().contains(ORA_ERR);
        }
    }
    
    
    public class CauseFinder {
    
       private ThrowablePredicate predicate;
    
       public CauseFinder(ThrowablePredicate predicate) {
          this.predicate = predicate;
       }
    
       Throwable findCause(Throwable t) {
          Throwable cause = t.getCause();
    
          return cause == null ? null 
             : predicate.accept(cause) ? cause : findCause(cause)
       }
    }
    
    
    // Your method
    private String getErrorOracle(Throwable e){
        return new CauseFinder(new OracleErrorThrowablePredicate()).findCause(e);
    }
    

提交回复
热议问题