我正在尝试使用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
答案 0 :(得分:3)
您从错误的软件包-{
"_id" : ObjectId("5d81171b2c69f45ef459e082"),
"name" : "Art",
"items_in_cat" : 4
},
而不是ConstraintViolationException
中导入了javax.validation
。
请确保在org.hibernate.exception
中使用org.hibernate.exception.ConstraintViolationException
。