如何在Spring Boot中正确重写handleMethodArgumentNotValid

Mar*_*ing 6 java overriding exception spring-boot

我正在尝试重写该handleMethodArgumentNotValid方法。但我仍然收到错误:

Caused by: java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]

我已经按照各种帖子中的建议覆盖了该方法(例如在Spring Rest ErrorHandling @ControllerAdvice / @Valid中),如下所示:

@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) {
        String message = errorMessageBuilder(ex);
        return handleExceptionInternal(ex, message, new HttpHeaders(), HttpStatus.UNPROCESSABLE_ENTITY, webRequest);
    }
}

Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

真挚地,

马塞尔

小智 7

如果您想创建自己的响应,请尝试使用以下代码。

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
        Map<String, Object> body = new HashMap<>();
        body.put("error", ex);
        return new ResponseEntity<>(body, HttpStatus.UNPROCESSABLE_ENTITY);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以将地图更改为您的自定义对象并设置您想要的错误信息。我希望它会起作用。

  • 是的,我现在已经找到了工作方法。要么不扩展 ResponseEntityExceptionHandler,要么如果您扩展该类,则删除 @ExceptionHandler(MethodArgumentNotValidException.class) 也可以。 (3认同)