How to handle errors in Spring reactor Mono or Flux?

后端 未结 5 2157
难免孤独
难免孤独 2021-01-05 17:02

I have below code retuning Mono:

try {
    return userRepository.findById(id)  // step 1
        .flatMap(user -> barRepository.findByUserId( u         


        
5条回答
  •  Happy的楠姐
    2021-01-05 17:30

    Use Exceptions.propagate(e) which wraps a checked exception into a special runtime exception that can be handled by onError

    Below Code tries to covers User attributes in upper case. Now, when it encounters kyle the checked exception is throws and MIKE is returned from onErrorReturn

    @Test
    void Test19() {
        Flux.fromIterable(Arrays.asList(new User("jhon", "10000"),
                new User("kyle", "bot")))
            .map(x -> {
                try {
                    return toUpper(x);
                } catch (TestException e) {
                    throw Exceptions.propagate(e);
                }
            })
            .onErrorReturn(new User("MIKE", "BOT")).subscribe(x -> System.out.println(x));
    }
    
    protected final class TestException extends Exception {
        private static final long serialVersionUID = -831485594512095557L;
    }
    
    private User toUpper(User user) throws TestException{
        if (user.getName().equals("kyle")) {
            throw new TestException();
        }
        return new User(user.getName().toUpperCase(), user.getProfession().toUpperCase());
    }
    

    Output

    User [name=JHON, profession=10000]
    User [name=MIKE, profession=BOT]
    

提交回复
热议问题