我正在关注这个example(Validate Request Body and Parameter in Spring Boot in medium)和这个example来实现一个处理程序来处理JSON作为参数的正确性。这些概念有点清楚,但是到了这一点,对
handleMethodArgumentNotValid
方法使用 @Override 给我一个错误,如:Method does not override method from its superclass.
我在网上搜索过如何解决这个问题,但我可能遗漏了一些东西。
package com.tericcabrel.hotel.exceptions;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
Map<String, List<String>> body = new HashMap<>();
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
body.put("errors", errors);
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
}
如果可能其他人遵循教程,我会报告解决方案。在official documentation方法(
ResponseEntityExceptionHandler
)报告班级HttpStatusCode
而不是HttpStatus
我今天遇到了类似的问题。
我已经解决了它 NOT 从 ResponseEntityExceptionHandler 扩展,用 @ExceptionHandler(MethodArgumentNotValidException.class) 替换 @Override 注释,并从方法中删除参数 headers 和 status。
我没有尝试你的特定代码。也许你需要稍微修改一下,但基本上你应该这样写:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, WebRequest request) {
Map<String, List<String>> body = new HashMap<>();
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
body.put("errors", errors);
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
}