【发布时间】:2018-03-24 17:23:59
【问题描述】:
为了简化我的错误处理,我想要一个 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)
}
}
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()
}
它被调用了。
除了第一个版本需要参数和特定标头之外,我不太明白有什么区别。
24.03.2018 更新
问题似乎是,如果客户端请求格式错误,则不会调用 ExceptionHandler。
默认情况下,格式错误的请求会导致非常详细的错误报告,但自定义 ExceptionHandler 似乎禁用了此功能。
【问题讨论】:
-
当您调用
closeLobby()时,您是否在日志中看到异常? -
不,我什么都没看到。
-
你得到什么 http 响应? 404?
-
我收到 400 响应。但是,它不是来自我的例外,因为即使我在那边改变它,我也会得到 400。
-
听起来您只是没有正确提出请求。如果删除异常并返回正确的值会发生什么?
标签: java spring rest exception kotlin