首页 > 解决方案 > 如何在 Spring Boot 中正确覆盖 handleMethodArgumentNotValid

问题描述

我正在尝试覆盖该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);
    }
}

我究竟做错了什么?

真挚地,

马塞尔

标签: javaspring-bootexceptionoverriding

解决方案


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

@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);
    }
}

您可以将 Map 更改为您的自定义对象并设置所需的错误信息。我希望它会奏效。


推荐阅读