Home > Software engineering >  ControllerAdvice does not handle thrown Exception
ControllerAdvice does not handle thrown Exception

Time:09-16

in my InvitationService file an exception thrown.

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

I defined an Custom Exception like this

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

Here is my controller

@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);
    }
}

and ControllerAdvice Class

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);
    }
}

Question is, when an exception in service occurs, Still status code 500 thrown and when I debug, it does not enter through a breakpoint in the ControllerExceptionHandler

CodePudding user response:

I am not sure, but try to use @RestControllerAdvice instead of @ControllerAdvice on your exception handler class.

@RestControllerAdvice
public class ControllerExceptionHandler  {

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

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

CodePudding user response:

You could try to create exception handler like this (add WebRequest as input parameter to your method):


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

       // your code here with breakpoint
       
    }
}

  • Related