ControllerAdvice 不处理抛出的异常

问题描述 投票:0回答:3

在我的 InvitationService 文件中抛出异常。

if (response != null && response.getStatus() == HttpStatus.SC_CONFLICT) {
        throw new UserAlreadyExistException("User Already Exists");
}

我这样定义了一个自定义异常

public class UserAlreadyExistException extends RuntimeException{
    public UserAlreadyExistException(String message) {
        super(message);
    }
}

这是我的控制器

@RestController
@RequestMapping("/invitations")
@Api(value = "Invitation APIs")
public class InvitationController {

 @Autowired
 InvitationService invitationService;

@PostMapping
@ApiOperation(value = "Invite tenant user")
public ResponseEntity<InvitationResponseDTO> inviteTenantUser(@RequestBody InvitationRequestDTO invitationRequestDTO) {

        invitationService.invite(invitationRequestDTO);
        return new ResponseEntity<>(new InvitationResponseDTO("success"), HttpStatus.OK);
    }
}

和 ControllerAdvice 类

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@ControllerAdvice()
public class ControllerExceptionHandler  {

    @ExceptionHandler(UserAlreadyExistException.class)
    public ResponseEntity<Object> handleUserAlreadyExistException(UserAlreadyExistException ex) {

        return new ResponseEntity<>(ex.getMessage(), HttpStatus.CONFLICT);
    }
}

问题是,当服务出现异常时,仍然抛出状态码500,而我调试时,并没有通过断点进入

ControllerExceptionHandler

java spring spring-mvc
3个回答
2
投票

我不确定,但尝试在您的异常处理程序类上使用

@RestControllerAdvice
而不是
@ControllerAdvice

@RestControllerAdvice
public class ControllerExceptionHandler  {

  @ExceptionHandler(value = UserAlreadyExistException.class)
  public ResponseEntity<Object> 
  handleUserAlreadyExistException(UserAlreadyExistException ex) {

      return new ResponseEntity<>(ex.getMessage(), HttpStatus.CONFLICT);
  }
}

0
投票

我很确定 ControllerAdvice 只处理 RuntimeException 性质的异常,Exception 是检查性质的,因此必须显式捕获然后包装为 ControllerAdvice 处理它的运行时。


-1
投票

您可以尝试像这样创建异常处理程序(将 WebRequest 作为输入参数添加到您的方法):


@ControllerAdvice
public class ControllerExceptionHandler {
  
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<Object> handleInputException(CustomException exception, WebRequest webRequest) {

       // your code here with breakpoint
       
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.