java 如何在Sping Boot 中正确覆盖handleMethodArgumentNotValid

q3qa4bjr  于 2023-04-28  发布在  Java
关注(0)|答案(2)|浏览(184)

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

我做错了什么?
真诚的
马塞尔

b4qexyjb

b4qexyjb1#

如果你想创建自己的响应,那么试试下面的代码。

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

xa9qqrwz

xa9qqrwz2#

请检查是否导入了正确的httpHeaders i。即,来自org。SpringFrameworkhttp.HttpHeaders,它对我有效。..

相关问题