我有一个简单的控制器:如何在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状态设置为响应?
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