@ControllerAdvice не работает Spring 5.1.6 - PullRequest
0 голосов
/ 19 сентября 2019

Я пытаюсь реализовать обработчик ошибок в Spring с Kotlin, но похоже, что приложение не распознает его: я всегда получаю страницу /error, а исключение не обрабатывается.

@EnableWebMvc, предложенный в других подобных вопросах, не работал для меня.

Это мой действительный код:

@ControllerAdvice
class UserExceptionHandler {

     @ExceptionHandler(ConstraintViolationException::class)
     fun methodArgumentTypeMismatchException(e: ConstraintViolationException): ResponseEntity<*> {
         return ResponseEntity
            .status(HttpStatus.FORBIDDEN)
            .body("Constraints Involved. Pay Attention To The Parameters")
     }
}

Ниже мой @RestController:

@RestController
@RequestMapping("/api")
class UserController (@Autowired private val userRepository: UserRepository) {

     @PostMapping("/new-user")
     fun createNewUser(@RequestParam mailAddress: String,
                       @RequestParam password: String): ResponseEntity<UserEntity> =
         ResponseEntity.ok(userRepository.saveAndFlush(UserEntity(mailAddress = mailAddress, password = password)))
}

UserEntity выдает исключение в случае неуникальных писем:

@Entity
data class UserEntity(
        @Id @NotBlank @GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Long? = null,

        @Column(unique=true) @NotBlank
        val mailAddress: String,

        @NotBlank
        var password: String
)

Что я делаю не так?Файлы, которые я показал, используют один и тот же пакет.

РЕДАКТИРОВАТЬ: Ниже приведена трассировка стека в Spring LOG

ERROR 32916 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["UK_KQE6HHKTR4W4E02H0KN61F442_INDEX_F ON PUBLIC.USER_ENTITY(MAIL_ADDRESS) VALUES ('asd@lol.it', 97)"; SQL statement:
insert into user_entity (id, mail_address, password) values (null, ?, ?) [23505-197]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

WARN 33436 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Failure in @ExceptionHandler public org.springframework.http.ResponseEntity<?> unito.taas.project.user.UserExceptionHandler.methodArgumentTypeMismatchException(javax.validation.ConstraintViolationException)

java.lang.IllegalStateException: Could not resolve parameter [0] in public org.springframework.http.ResponseEntity<?> unito.taas.project.user.UserExceptionHandler.methodArgumentTypeMismatchException(javax.validation.ConstraintViolationException): No suitable resolver

1 Ответ

2 голосов
/ 19 сентября 2019

Вы импортируете ConstraintViolationException из неправильной упаковки - javax.validation вместо org.hibernate.exception.

Обязательно используйте org.hibernate.exception.ConstraintViolationException в UserExceptionHandler.

...