【发布时间】:2017-09-26 12:09:44
【问题描述】:
我遇到了 Spring(和 kotlin?)的问题,我的全局错误处理程序无法捕获自定义转换器中引发的任何异常。
我知道spring默认支持string->UUID映射,但我想明确检查是否真的抛出了异常。它是以下转换器。无论有没有我自己实现的转换器,行为都是相同的。
我的 WebMvcConfiguration 如下所示:
@Configuration
class WebMvcConfiguration : WebMvcConfigurerAdapter() {
override fun addFormatters(registry: FormatterRegistry) {
super.addFormatters(registry)
registry.addConverter(Converter<String, UUID> { str ->
try {
UUID.fromString(str)
} catch(e: IllegalArgumentException){
throw RuntimeException(e)
}
})
}
这是我的 GlobalExceptionHandler: (它还包含其他处理程序,为简洁起见,我省略了)
@ControllerAdvice
class GlobalExceptionHandler : ResponseEntityExceptionHandler() {
@ExceptionHandler(Exception::class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
fun handleException(ex: Exception): ApiError {
logger.info(ex.message, ex)
return ApiError(ex.message)
}
}
最后是控制器:
@Controller
class MyController : ApiBaseController() {
@GetMapping("/something/{id}")
fun getSomething(@PathVariable("id") id: UUID) {
throw NotImplementedError()
}
}
控制器内部的异常(例如 NotImplementedError)方法被很好地捕获。但是当传递无效的 UUID 时,转换器内抛出的 IllegalArgumentException 被吞下,spring 返回一个空的 400 响应。
我现在的问题是:如何捕获这些错误并使用自定义错误消息进行响应?
提前致谢!
【问题讨论】:
-
非常感谢您解释反对票的用途。
标签: spring spring-mvc kotlin