-1

I'm new to reactive programming I want to save the object to the DB when handling an error, but as far as I know, calling the block() method is not the best practice

 mailFailureRepository.save(failure).block();

Is there a way to do this without interrupting the flow? I think I should rebuild the thread chain, but I don't quite understand how to do it in my case

I will also be glad of any information resources

  public Mono<Object> sendEmail(SendEmailRequest request)
          throws MailTemplateNotSupportedException, ExactTargetException {
        log.debug("Send email process started.");
        return validateRequestAndSendMail(request)
            .onErrorResume(error -> {
              if (error instanceof ExactTargetException ex) {
                MailFailure failure = MailFailure.builder()
                    .templateKey(request.getTemplateKey())
                    .templateParams(request.getTemplateParams() != null ? request.getTemplateParams().toString() : null)
                    .subscriberHash(request.getSubscriberHash())
                    .email(request.getEmail())
                    .responseStatus(ex.getStatus())
                    .responsePayload(ex.getBody())
                    .build();
                mailFailureRepository.save(failure).block();
                return Mono.error(error);
              }
              return Mono.error(error);
            });

1 Answers1

-1

Why not save and then return error without blocking:

        public Mono <Object> sendEmail(SendEmailRequest request)
                throws MailTemplateNotSupportedException, ExactTargetException {
            log.debug("Send email process started.");
            return validateRequestAndSendMail(request)
                    .onErrorResume(error -> {
            Mono<Object> errorMono = Mono.error(error);
            if (error instanceof ExactTargetException ex) {
                return mailFailureRepository.save(buildFailureEmail(request))
                        .thenReturn(errorMono);
            }
            return errorMono;
            });
        }
        private MailFailure buildFailureEmail(SendEmailRequest request) {
            return MailFailure.builder()
                .templateKey(request.getTemplateKey())
                .templateParams(request.getTemplateParams() != null ? request.getTemplateParams().toString() : null)
                .subscriberHash(request.getSubscriberHash())
                .email(request.getEmail())
                .responseStatus(ex.getStatus())
                .responsePayload(ex.getBody())
                .build();
        }
  • this code wont work, you need a return statemant `return mailFailureRepository.save(buildFailureEmail(request)) .thenReturn(errorMono);` as `thenReturn` will throw away what is returned from `save` function but it wont return from the function. – Toerktumlare Feb 06 '23 at 18:13
  • I misses `return statement`. Thanks – Elyorbek Ibrokhimov Feb 06 '23 at 22:27