如何将已检查的异常从CompletableFuture传递到ControllerAdvice

问题描述 投票:1回答:1

如何使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();
    }

}
java spring java-8 completable-future controller-advice
1个回答
0
投票

我会说您使用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";
    });
© www.soinside.com 2019 - 2024. All rights reserved.