2017-07-21 67 views
0
逃生的實例

我在休息控制器在UncaughtExceptionHandler的

public DeferredResult<String> getWashHistory(@RequestParam(value = "sid", required = true, defaultValue = "") String sid, 
      HttpServletResponse response, HttpServletRequest request, 
      @RequestParam(value = "sort", defaultValue = "") String sortType, 
      @RequestParam(value = "order", defaultValue = "") String order, 
      @RequestParam(value = "limit", defaultValue = "") String limit, 
      @RequestParam(value = "offset", defaultValue = "") String offset) { 

     System.out.println("Thread: " + Thread.currentThread()); 
     final Integer managerId = checkSession(sid); 
     DeferredResult<String> defResult = new DeferredResult<>(); 
     new Thread(() -> { 
      System.out.println("tert: " + Thread.currentThread()); 
      Thread.currentThread().setUncaughtExceptionHandler(new SeparateThreadsExceptionHandler(defResult)); 
      final String result = washController.getWashHistory(managerId, order, sortType, limit, offset); 
      defResult.setResult(result); 
     }).start(); 
     return defResult; 
    } 

內getWashHistory下面的方法,我把我的自定義異常命名爲InvalidUserInputException,來處理這個例外,我有下面的類

public class SeparateThreadsExceptionHandler implements Thread.UncaughtExceptionHandler{ 
    private DeferredResult<String> dr; 
    public SeparateThreadsExceptionHandler(DeferredResult<String> dr){ 
     this.dr = dr; 
    } 
    @Override 
    public void uncaughtException(Thread t, Throwable e) { 
     if(e instanceof InvalidUserInputException){ 
      InvalidUserInputException throwableException = (InvalidUserInputException)e; 
      dr.setResult(throwableException.error().getErrorCode()); 
     } else { 
      throw new UnknownException("Unknown exception", "unKnown", "unKnown", null); 
     } 

問題是,在項目中我有很多自定義異常,是否可以避免使用public void uncaughtException(Thread t, Throwable e)中的實例在所有異常之間進行切換?

回答

0

您可以使用繼承這個如下圖所示

class ParentException extends Exception { 
     // based on .error() call showin in example, I am assuming you have some 
     // class that holds error code. 
     private Error error; 
} 

那麼孩子的異常會

class InvalidUserInputException extends ParentException { 
// create constructor here that builds Error. 
} 

最後,

if(e instanceof ParentException) { 
    ParentException throwableException = (ParentException)e; 
      dr.setResult(throwableException.error().getErrorCode()); 
} 
+0

謝謝你,這正是我「M尋找 –

相關問題