我正在尝试重写handleMethodArgumentNotValid
方法。但我仍然收到错误:
由以下原因引起:java.lang.IllegalStateException:为[class org.springframework.web.bind.MethodArgumentNotValidException]映射的@ExceptionHandler方法不明确
我已经按照各种帖子(例如 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 更改为您的自定义对象并设置您想要的错误信息。我希望它会起作用。
关于java - 如何在Spring Boot中正确重写handleMethodArgumentNotValid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59952013/