【问题标题】:How to override handleMethodArgumentNotValid properly in Spring Boot如何在 Spring Boot 中正确覆盖 handleMethodArgumentNotValid
【发布时间】:2020-01-28 15:27:29
【问题描述】:

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

我做错了什么?

此致,

马塞尔

【问题讨论】:

  • 错误信息提到了歧义。听起来同一个异常类有多个异常处理程序,编译器不会随机选择一个。不过我不知道解决方案。
  • 我知道消息是什么意思,Spring也在内部处理它,这就是为什么我要覆盖它(首先扩展类,然后覆盖它。)
  • @MarcelOostebring 请检查我的回答,这将帮助你stackoverflow.com/a/57961101/10426557 如果这有助于投票请...
  • @一个不幸没有帮助我的人。我仍然收到模棱两可的异常处理程序方法映射错误。
  • 可能对某人有所帮助,我已经解决了这个问题:stackoverflow.com/a/68888906/3412696

标签: java spring-boot exception overriding


【解决方案1】:

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

@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 更改为您的自定义对象并设置您想要的错误信息。我希望它会起作用。

【讨论】:

  • 是的,我现在已经找到了一种工作方式。要么不扩展 ResponseEntityExceptionHandler,要么如果你扩展了那个类,删除 @ExceptionHandler(MethodArgumentNotValidException.class) 也可以。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-01
  • 2011-05-28
  • 2016-06-06
  • 2015-09-20
  • 2016-02-07
  • 2023-02-16
  • 2019-11-21
相关资源
最近更新 更多