java - 如何在 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);
}
}
我究竟做错了什么?
真挚地,
马塞尔
解决方案
如果您想创建自己的响应,请尝试使用以下代码。
@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 更改为您的自定义对象并设置所需的错误信息。我希望它会奏效。
推荐阅读
- jquery - jquery自动完成选择事件,显示动作数据
- gstreamer - Gstreamer gst-launch-1.0 选择音频流进行转码
- corda - 是什么让 Corda X500 的名称与众不同?
- javascript - 改变全模态的颜色
- wpf - WPF &XAML:如何将颜色属性绑定到画笔
- swiftcharts - “SwiftChart”pod 库在 Chart.swift 文件中有错误
- java - 如何使用他们在 Firebase 实时数据库中保存的 ID 从另一个表中获取数据
- javascript - 如何定位数组中的对象子集并将属性更改为每个对象的递增数字?
- javascript - 在 Fetch JS for Django 中添加 CSRF
- c# - 具有数据绑定和额外价值的组合框