Kotlin - Spring REST - 带有 ExceptionHandler 的 ControllerAdvice 不会被调用

Mar*_*cel 5 java rest spring exception kotlin

为了简化我的错误处理,我想要一个 ExceptionHandler,我在http://www.baeldung.com/exception-handling-for-rest-with-spring上使用了 4. 点。

我的异常处理程序类如下所示:

@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)
    }
}
Run Code Online (Sandbox Code Playgroud)

TestException只是一个简单的Exception扩展RuntimeException

class TestException : RuntimeException()
Run Code Online (Sandbox Code Playgroud)

无论如何,在我RestController的情况下,只要有任何调用,我就会抛出异常:

@GetMapping("/lobby/close")
fun closeLobby(@RequestParam(value = "uuid") uuid: String, @RequestHeader(value = "userSession") userSession: String): ResponseEntity<Any> {
    throw TestException()
}
Run Code Online (Sandbox Code Playgroud)

但是不调用异常处理程序。

但是,调用这个:

@GetMapping("/lobby/error")
fun error(): ResponseEntity<Any> {
    throw TestException()
}
Run Code Online (Sandbox Code Playgroud)

它被调用。

除了第一个版本需要参数和特定标题之外,我不太明白有什么区别。

更新 24.03.2018

问题似乎是,如果客户端请求格式错误,则不会调用 ExceptionHandler。

默认情况下,格式错误的请求会导致非常详细的错误报告,但自定义 ExceptionHandler 似乎禁用了此功能。

sil*_*udo 12

我让它工作了,这是我的代码。

@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)
    }
}
Run Code Online (Sandbox Code Playgroud)

异常类

class UserAlreadyExistsException(override val message: String?) : Exception(message)
Run Code Online (Sandbox Code Playgroud)

数据类

data class ErrorsDetails(val time: Date, val message: String, val details: String)
Run Code Online (Sandbox Code Playgroud)

我的控制器:

@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)
    }
Run Code Online (Sandbox Code Playgroud)


Mar*_*cel 0

现在我有一个解决方案,尽管这不应该是我认为的理想方式。

由于我的控制器无论如何都没有基类,所以我没有创建包含BaseController处理异常的函数,这些函数只是简单地注释,ExceptionHandler并且它们的方法列表包含Exception它们应该处理的方法。

由于该类BasicController没有扩展任何其他处理异常的 Spring 类,因此它不会覆盖处理格式错误请求等问题的默认行为。

我很乐意接受任何更好的解决方案,因为我认为这不应该是理想的方式。