java ControllerAdvice不处理抛出的异常

xurqigkl  于 2023-04-04  发布在  Java
关注(0)|答案(3)|浏览(191)

在我的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中的断点进入

svujldwt

svujldwt1#

我不确定,但是尝试在异常处理程序类上使用@RestControllerAdvice而不是@ControllerAdvice

@RestControllerAdvice
public class ControllerExceptionHandler  {

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

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

0g0grzrc2#

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

o7jaxewo

o7jaxewo3#

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

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

       // your code here with breakpoint
       
    }
}

相关问题