我有一個帶有發(fā)布請求的控制器。我正在嘗試使用簡單的 NotNull 注釋來驗證 POJO。我正在使用 ControllerAdvice 來處理異常。@PostMapping("/something")public MyResponse post(@Valid MyRequest request) { // nevermind...}public class MyRequest { @NotNull private Integer something; // Getters setters nevermind...}@ControllerAdvicepublic class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(value = BindException.class) protected ResponseEntity<Object> handleBindException(RuntimeException ex, WebRequest request) { return handleExceptionInternal(...); }}所以我正在嘗試使用它,但是當我啟動應用程序時,我得到了以下信息:org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerExceptionResolver]: Factory method 'handlerExceptionResolver' threw exception; nested exception is java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.validation.BindException]: {protected org.springframework.http.ResponseEntity com.liligo.sponsoredads.controller.RestResponseEntityExceptionHandler.handleBindException(java.lang.Exception,org.springframework.web.context.request.WebRequest), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest) throws java.lang.Exception}所以我想為 BindExceptions 創(chuàng)建自己的處理程序,但是當我為 BindException 類創(chuàng)建 ExceptionHandler 時,spring 應用程序沒有啟動。如果我注釋掉handleBindException 方法,應用程序將啟動,如果發(fā)生BindException,它只會返回400 并注銷錯誤,但沒有任何內容作為響應正文發(fā)回。為 BindExceptions 創(chuàng)建自定義處理程序的解決方案是什么?
1 回答

江戶川亂折騰
TA貢獻1851條經驗 獲得超5個贊
我發(fā)現(xiàn)問題是因為 ResponseEntityExceptionHandler 已經有一個方法來處理 BindExceptions。這意味著您不能為此“覆蓋”異常處理。許多異常也是如此(參見類 ResponseEntityExceptionHandler:106)。因此,如果您想創(chuàng)建自己的綁定異常處理程序,則需要覆蓋超類中處理它的方法。它看起來像這樣:
@Override
protected ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
return handleExceptionInternal(...);
}
有了它,您可以退回任何您需要的東西。所以我只找到了這個解決方案,如果有人知道其他解決方案,請不要猶豫在這里寫:)
添加回答
舉報
0/150
提交
取消