2017-09-26 52 views
-1

我面臨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響應。

我現在的問題是:如何捕獲這些錯誤並用自定義錯誤信息回覆?

在此先感謝!

+0

的解釋什麼downvote爲將高度讚賞。 –

回答

0

我有同樣的問題。春天吞下任何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); 
    } 

} 
+0

謝謝!擴展ResponseEntityExceptionHandler也是我的問題。刪除它解決了這個問題。 –

0

一些試驗和錯誤之後,我找到了解決辦法:

而不是使用@ControllerAdvice,實現BaseController別人繼承並添加異常處理程序有工作的。

所以我的基本控制器是這樣的:

abstract class ApiBaseController{ 

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

} 

如果任何人都可以在它爲什麼是這樣的,而不是其他的方式闡述,請這樣做,因爲我接受將迎來你的答案。