2017-08-28 107 views
1

我有一個簡單的控制器:如何在Spring中使用CompletableFuture.exceptionaly()時更改響應statuc代碼?

@RestController 
public class SimpleController() { 

    public String get() { 
     if (System.nanoTime() % 2 == 0) 
      throw new IllegalArgumentException("oops"); 

     return "ok" 
    } 
} 

控制器可以拋出簡單的異常,所以我寫控制器顧問爲它處理:

@ExceptionHandler(IllegalArgumentException.class) 
@ResponseBody 
public ResponseEntity<String> rejection(Rejection ex) { 
    return new ResponseEntity<>("bad", HttpStatus.CONFLICT); 
} 

現在我要讓get方法異步。但我不知道處理異常的最佳方法。

我想:

public CompletableFuture<String> get() { 
     CompletableFuture.supplyAsync(
      () -> { 
       if (System.nanoTime() % 2 == 0) 
        throw new IllegalArgumentException("oops"); 

       return "ok"; 
      }).exceptionally(thr -> { 
       //what should i do? 
       if (thr instanceof IllegalArgumentException) 
        throw ((IllegalArgumentException) t); 

       if (thr.getCause() instanceof IllegalArgumentException) 
        throw ((IllegalArgumentException) t.getCause()); 

       return null; 
      } 
    } 

但是控制器顧問仍然沒有捕獲異常。

另外我試着返回ResponseEntity(「message」,HttpStatuc.CONFLICT);在特別封鎖。 但在測試中,我仍然有MvcResult.getResponse()。getStatus()== 200.

任何其他的想法? 也許這是一種錯誤的方式呢?

UPDATE 我不知道爲什麼,但它不捕獲異常:

@Override 
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { 
    return new AsyncUncaughtExceptionHandler() { 
     @Override 
     public void handleUncaughtException(Throwable ex, Method method, Object... params) { 
      System.out.println(); 
     } 
    }; 

即使它的工作,如何HTTP狀態設置爲響應?

+0

http://javasampleapproach.com/java/java-8/java-8-completablefuture-handle-exception – Optio

+0

.handle()與.exceptionally()幾乎相同,只是它調用所有時間。所以我仍然不知道如何改變異步響應的HttpStatus。 – DamienMiheev

+0

https://stackoverflow.com/questions/44138199/spring-exceptionhandler-and-multi-threading – Optio

回答

0

試圖返回一個ResponseEntity實例:

return new ResponseEntity<>("bad", HttpStatus.CONFLICT); 

exceptionally方法。

+0

我應該在哪裏返回? – DamienMiheev

+0

異常(thr - > new ResponseEntity <>(「bad」,HttpStatus.CONFLICT)); –

相關問題