Home > OS >  Cannot catch the exception through @ControllerAdvice and @ExceptionHandler in CRUD application
Cannot catch the exception through @ControllerAdvice and @ExceptionHandler in CRUD application

Time:12-03

I am trying to create custom exceptionhandler but it is not catching my exception (UserAlreadyExistsException; UserNotFoundException is working very well). I`ve read another questions but these advices did not help me out. My controller advice class is the following:

@RestControllerAdvice
public class UserExceptionHandler extends ResponseEntityExceptionHandler {

    private ResponseEntity<ErrorDTO> handleCommonHelper(final Exception exception, final HttpStatus status) {
        final var errorDto = new ErrorDTO();
        errorDto.setCode(String.valueOf(status.value()));
        errorDto.setErrorDetails(exception.getMessage());
        return new ResponseEntity<>(errorDto, status);
    }

    @ExceptionHandler(value = {UserNotFoundException.class})
    public ResponseEntity<ErrorDTO> handleUserNameNotFoundConflict(final UserNotFoundException e) {
        return this.handleCommonHelper(e, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(value = {UserAlreadyExistsException.class})
    public ResponseEntity<ErrorDTO> handleUserNameExistsConflict(final UserAlreadyExistsException e) {
        return this.handleCommonHelper(e, HttpStatus.CONFLICT);
    }
}

My method create looks like the following:

 @Override
public UserDTO createUser(UserDTO userDTO) {
    var databaseUser = userRepository.existsById(Long.valueOf(userDTO.getUsername()));
    if (databaseUser) {
        throw new UserAlreadyExistsException("User with this username already exists!");
    }
    userDTO.setId(null);
    var userEntity = mapToUserEntity(userDTO);
    return mapToUserDTO(userRepository.save(userEntity));
}

And my controller:

@ApiResponses(value = {
        @ApiResponse(responseCode = "201", description = "Created")
        @ApiResponse(responseCode = "400", description = "Client error"),
        @ApiResponse(responseCode = "500", description = "Server error")
})
@Operation(summary = "Creation of user", description = "Creation of user")
@PostMapping("/users")
public ResponseEntity<UserDTO> createUser(@RequestBody UserDTO userDTO) {
    var createdUser = userService.createUser(userDTO);
    return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
}

Well, now I can create several users with the same username and get 201 code. Could you give me the piece of advice - how can I catch this exception?

CodePudding user response:

Looks like there is an error in logic: It is seems to me that databaseUser is always false.

var databaseUser = userRepository.existsById(Long.valueOf(userDTO.getUsername()));
    if (databaseUser) {

You try to get user from database by Id, but you are using username. Looks like it should be smth like this:

var databaseUser = userRepository.existsByUsername(userDTO.getUsername()); 

You have to check user for existing by unique for user fields (if in your system username is unique, you have to check by username)

  • Related