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

标签 java spring rest exception kotlin

为了简化我的错误处理,我想要一个 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/

相关文章:

java - 如何将一组坐标约束到圆形区域?

java - 公共(public)方法中的LazyInitializationException标记为@Transactional,并从另一个bean调用

Spring MVC 3.0 : How do I bind to a persistent object

java - 如何在 spring-boot 项目中的 pom.xml 添加非 spring-boot 依赖

java - Swagger 不生成 REST 文档

java - 最RESTful文件发送Java Spring

Java泛型方法调用

java - 如何将字符添加到用户光标所在的 EditText

spring - 为什么 spring 集成中默认的 "errorChannel"是 "PublishSubscribeChannel"?

javascript - 通过 REST API 响应 native /Spring Boot,值为 0 或 null