我面臨Spring(和kotlin?)的問題,其中我的全局錯誤處理程序不會捕獲自定義轉換器中引發的任何異常。Spring框架吞下自定義轉換器的異常
我知道spring默認支持string-> UUID映射,但是我想明確地檢查一個異常是否實際拋出。它是下面的轉換器。這種行爲與我自己實現的轉換器沒有相同之處。
我WebMvcConfuguration如下所示:
@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: (還包含其他處理程序,這是我ommitted爲簡潔起見)
@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()
}
}
控件內部的異常ler(例如NotImplementedError)方法被捕獲得很好。但是,當傳遞無效UUID時,在轉換器中拋出的IllegalArgumentException被吞下,並且spring將返回一個空的400響應。
我現在的問題是:如何捕獲這些錯誤並用自定義錯誤信息回覆?
在此先感謝!
的解釋什麼downvote爲將高度讚賞。 –