为了简化我的错误处理,我想要一个 ExceptionHandler,我使用了 4.point on http://www.baeldung.com/exception-handling-for-rest-with-spring .
我的异常处理程序类如下所示:
@ControllerAdvice
class APIExceptionHandler : ResponseEntityExceptionHandler() {
@ExceptionHandler(value = [(TestException::class)])
fun handleConflict(exception: TestException, request: WebRequest): ResponseEntity<Any> {
println("Handle")
return handleExceptionInternal(exception, "Response Body", HttpHeaders(), HttpStatus.BAD_REQUEST, request)
}
}
TestException
只是一个简单的 Exception
扩展 RuntimeException
class TestException : RuntimeException()
无论如何,在我的 RestController
中,我只是在进行任何调用时立即抛出异常:
@GetMapping("/lobby/close")
fun closeLobby(@RequestParam(value = "uuid") uuid: String, @RequestHeader(value = "userSession") userSession: String): ResponseEntity<Any> {
throw TestException()
}
但是没有调用异常处理器。
但是,调用这个:
@GetMapping("/lobby/error")
fun error(): ResponseEntity<Any> {
throw TestException()
}
它被调用。
除了第一个版本需要参数和特定 header 之外,我不太明白有什么区别。
2018 年 3 月 24 日更新
问题似乎是,如果客户端请求格式错误,则不会调用 ExceptionHandler。
默认情况下,格式错误的请求会导致非常详细的错误报告,但自定义 ExceptionHandler 似乎禁用了此功能。
最佳答案
我成功了,这是我的代码。
@ControllerAdvice
class ControllerAdviceRequestError : ResponseEntityExceptionHandler() {
@ExceptionHandler(value = [(UserAlreadyExistsException::class)])
fun handleUserAlreadyExists(ex: UserAlreadyExistsException,request: WebRequest): ResponseEntity<ErrorsDetails> {
val errorDetails = ErrorsDetails(Date(),
"Validation Failed",
ex.message!!
)
return ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST)
}
}
异常类
class UserAlreadyExistsException(override val message: String?) : Exception(message)
数据类
data class ErrorsDetails(val time: Date, val message: String, val details: String)
我的 Controller :
@PostMapping(value = ["/register"])
fun register(@Valid @RequestBody user: User): User {
if (userService.exists(user.username)) {
throw UserAlreadyExistsException("User with username ${user.username} already exists")
}
return userService.create(user)
}
关于java - Kotlin - Spring REST - 不会调用带有 ExceptionHandler 的 ControllerAdvice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49467658/