0

我使用 javax.mail 依赖 spring-boot-starter-mail 并且我想覆盖用户在提供错误电子邮件或不存在域的电子邮件时收到的错误消息。如何从方法 getInvalidAddresses 覆盖 javax.mail.SendFailedException 的错误消息?我想覆盖并向用户传递一个很好的错误消息。我有自己的 GlobalExceptionClass,用于我的应用程序中的所有不同异常:

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

     @ExceptionHandler({SendFailedException.class})
     private ResponseEntity<MessageResponse> handleSendFailException(SendFailedException sfe){
     
       if (sfe.getInvalidAddresses() != null) {
          System.out.println("INVALID ADRESSS");
          return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new 
        MessageResponse("adress is inavlid"));
       }
       return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new 
       MessageResponse("invalidadress"));
       }
     }

我的控制器类

    @PostMapping("/offers")
public ResponseEntity<MessageResponse> mailOffer(@Valid @RequestBody OffersDto offersDto) throws 
    MessagingException {
    String succMessage = "success.";
    offersService.addOffer(offersDto);
    offersService.sendMail(offersDto);
    return ResponseEntity.ok(new MessageResponse(succMessage));
}

服务类

    public Offers sendMail(OffersDto offersDto) throws MessagingException  {
     ///messaging methods, attributes
    }

我只是复制了与其他方法相同的异常处理,但上面的代码不会覆盖异常消息

4

1 回答 1

0

您必须尝试/捕获已检查的异常并在捕获或最终阻止抛出新的未经检查的自定义异常,然后处理您的自定义异常(您必须将 MessagingException 的属性添加到您的自定义异常以检查语句)

@ExceptionHandler({CustomException.class})
于 2021-04-12T06:02:45.893 回答