Skip to content
Advertisement

return throw exception in Kotlin

I have the following problem, I can’t return this exception. It’s giving an error 500 and doesn’t run this exception. I wish that when I entered the if it would already return this custom exception.

KOTLIN

    class CustomExceptionName(message: String) : Exception(message)
     
        @PostMapping
        fun createUsers(@RequestBody user: User): ResponseEntity<User> {
            var pattern = Regex("[^0-9]")
            var emailExist = false
            emailExist = this.userRepository.existsByEmail(user.email)
            if (emailExist) {
              throw CustomExceptionName("email exist")
            }
            user.telephone = pattern.replace(user.telephone, "")
            return ResponseEntity.ok(this.userRepository.save(user))
        }

JAVA

      public class DomainException extends RuntimeException {
        private static final long serialVersionUID = 1L;

        public DomainException(String message) {
            super(message);
        }
    }

        @Override
        public Client create(Client client) {
            boolean clientExists = clientRepository.findByEmail(client.getEmail())
                    .stream()
                    .anyMatch(emailExists -> !emailExists.equals(client));
            boolean cnpjExists = clientRepository.findByCnpj(client.getCnpj())
                    .stream()
                    .anyMatch(emailExists -> !emailExists.equals(client));
            if(clientExists) {
                throw new DomainException("Já existe um cliente cadastrado com esse e-mail");
            }
            if(cnpjExists) {
                throw new DomainException("Já existe um cliente cadastrado com esse cnpj");
            }
            return clientRepository.save(client);
        }

Advertisement

Answer

You need to use RestControllerAdvice or ControllerAdvice like

@ControllerAdvice
class ControllerAdviceRequestError : ResponseEntityExceptionHandler() {

    @ExceptionHandler(value = [(CustomExceptionName::class)])
    fun handleCustomExceptionName(ex: CustomExceptionName,request: WebRequest): ResponseEntity<String> {
       
        return ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST)
    }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement