私はシンプルなコントローラがあります。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);
:
http://javasampleapproach.com/java/java-8/java-8-completablefuture-handle-exception – Optio
.handle()はすべての時間を呼び出す点を除き、.exceptionally()とほぼ同じです。だから私はまだ非同期応答のHttpStatusを変更するために熱い知らない。 – DamienMiheev
https://stackoverflow.com/questions/44138199/spring-exceptionhandler-and-multi-threading – Optio