Spring框架吞下自定义转换器的异常

我正面临Spring(和kotlin?)的一个问题,我的全局错误处理程序不会捕获在自定义转换器中引发的任何异常。

我知道春天默认支持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 :(它也包含其他处理程序,为简洁起见我省略)

 @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响应。

我现在的问题是:如何捕获这些错误,并用自定义错误信息回应?

提前致谢!

经过一些更多的尝试和错误,我找到了一个解决方案:

而不是使用@ControllerAdvice ,实现其他人继承的BaseController并添加异常处理程序。

所以我的基地控制器看起来像这样:

 abstract class ApiBaseController{ @ExceptionHandler(Exception::class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody fun handleException(ex: Exception): ApiError { return ApiError(ex.message) } } 

如果有人可以详细说明为什么它是这样的,而不是其他方式,请这样做,我会标记你的答案被接受。

我有同样的问题。 春天吞下任何IllegalArgumentExceptionConversionFailedException在我的情况)。

为了得到我正在寻找的行为; 即只处理列出的异常,对其他异常使用默认行为,则不得扩展ResponseEntityExceptionHandler

例:

 @ControllerAdvice public class RestResponseEntityExceptionHandler{ @ExceptionHandler(value = {NotFoundException.class}) public ResponseEntity<Object> handleNotFound(NotFoundException e, WebRequest request){ return new ResponseEntity<>(e.getMessage(), new HttpHeaders(), HttpStatus.NOT_FOUND); } }