2017-08-28 4 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ステータスを設定する方法? exceptionally方法のうち

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

+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インスタンスを返すようにしてください。

+0

私はそれを返すべきですか? – DamienMiheev

+0

例外的に(thr - >新しいResponseEntity <>( "悪い"、HttpStatus.CONFLICT)); –

0

申し訳ありませんが、問題はコードではありません。 私はちょうど悪いテストを書いた。 はここで説明するためのリンク:

https://sdqali.in/blog/2015/11/24/testing-async-responses-using-mockmvc/

ちょうど使用:

MvcResult result = mockMvc.perform(...).andReturn(); 
result = mockMvc.perform(asyncDispatch(result)).andReturn(); 

あなたは、ステータスや結果応答を確認する前に。

関連する問題