【发布时间】:2018-02-05 13:57:53
【问题描述】:
我有一个简单的控制器:
@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。
还有什么想法吗? 也许这是一个错误的方式?
更新 我不知道为什么,但它没有捕获异常:
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncUncaughtExceptionHandler() {
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
System.out.println();
}
};
即使它工作,如何设置http状态响应?
【问题讨论】:
-
.handle() 与 .exceptionally() 几乎相同,只是它始终调用。所以我仍然不知道要更改异步响应的HttpStatus。
-
仍然不适合我。 :(
标签: java spring spring-mvc asynchronous spring-boot