0

I have a custom exception that I throw in a class that is not caught in another class.

I don't know what's wrong here :

Class MailService.java

@Async
public void sendMail(String to, String subject) throws EmailNotSentException {
    throw new EmailNotSentException();
}

Class MailResource.java

@RequestMapping(value = "/mails-envoyes",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<MailEnvoye> createMailEnvoye(@RequestBody MailEnvoye mailEnvoye, HttpServletRequest request) throws URISyntaxException {
    try{
        mailService.sendMail(to, "subject");
    }catch (EmailNotSentException e){
        log.debug(e.getLocalizedMessage());
    }
}

Exception

public class EmailNotSentException extends MessagingException {

    public EmailNotSentException() {
        super();
    }
    public EmailNotSentException(String message) {
        super(message);
    }

    public EmailNotSentException(String message, Exception e) {
        super(message, e);
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
thomas
  • 1,201
  • 2
  • 15
  • 35
  • 2
    Are you sure you are running in debug? – mate00 Mar 20 '19 at 08:13
  • How are you sure that the other exceptions are also detected? – programmer-man Mar 20 '19 at 08:16
  • Have you tried catching Exception, to be sure anything is thrown at all ? – Mwak Mar 20 '19 at 08:16
  • 1
    @Async methods are executed in new thread so you can not catch exceptions by catch clause. Please read following Spring docs: https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#scheduling-annotation-support-exception – gerard Mar 20 '19 at 08:24
  • Same issue with Exception. I have an error in log console but it is not caught in the try catch. 20/03/2019 - 09:21 [ERROR] com.myapp.rh.aop.logging.LoggingAspect - Exception in com.myapp.rh.service.MailService.sendMail() with cause = null and exception {} java.lang.Exception: null at com.myapp.rh.service.MailService.sendMail(MailService.java:739) – thomas Mar 20 '19 at 08:24

1 Answers1

0

The issue is probably the @Async annotation (I'm assuming this code runs with Spring) ... as it says on the tin, it run it asynchronously, which means that it will run in a different thread, so the calling method will never receive the Exception.

If you want to handle the exception in the way you have in your code, just remove the @Async annotation.

There are a few articles around which explain how to catch an exception from an async method (google is your friend), and make it available so something else can deal with it, but it's always asynchronously.

Augusto
  • 28,839
  • 5
  • 58
  • 88