@ControllerAdvice 不工作 Spring 5.1.6

@ControllerAdvice not working Spring 5.1.6

我正在尝试使用 Kotlin 在 Spring 中实现错误处理程序,但应用程序似乎无法识别它:我总是得到 /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

您从错误的包中导入 ConstraintViolationException - javax.validation 而不是 org.hibernate.exception

确保在 UserExceptionHandler.

中使用 org.hibernate.exception.ConstraintViolationException