2

我正在尝试使用 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

4

1 回答 1

3

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

确保使用org.hibernate.exception.ConstraintViolationExceptionUserExceptionHandler.

于 2019-09-19T14:13:06.817 回答