如何使controllerAdvice类捕获从completablefutrue引发的异常。在下面的代码中,我有一个方法checkId
引发一个已检查的异常。我使用completablefuture调用此方法,并将选中的异常包装在CompletionException中。尽管我在控制器建议类中有一个处理程序方法,但是它没有处理错误。
@RestController
public class HomeController {
@GetMapping(path = "/check")
public CompletableFuture<String> check(@RequestParam("id") int id) {
return CompletableFuture.supplyAsync(() -> {
try {
return checkId(id);
}
catch (Exception e) {
throw new CompletionException(e);
}
});
}
public String checkId(int id) throws Exception {
if (id < 0) {
throw new MyException("Id must be greater than 0");
}
return "id is good";
}
}
-
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
-
@ControllerAdvice
public class ExceptionResolver {
@ExceptionHandler(value = CompletionException.class)
public String handleCompletionException(CompletionException ex) {
return ex.getMessage();
}
}
我会说您使用exceptionally方法来处理异步进程抛出的所有异常
public CompletableFuture<String> check(@RequestParam("id") int id) {
return CompletableFuture.supplyAsync(() -> {
try {
return checkId(id);
}
catch (Exception e) {
throw new CompletionException(e);
}
}).exceptionally(ex->{
return "Exception Thrown";
});