我尝试重写handleMethodArgumentNotValid方法,但没有成功。
我得到的错误是:"CustomResponseEntityExceptionHandler类型的方法handleMethodArgumentNotValid(方法参数无效异常,HttpHeaders,HttpStatus,WebRequest)必须重写或实现超类型,但我不知道为什么我还没有这样做。
我是这么做的:
@ControllerAdvice
@RestController
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
var exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<Object>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return new ResponseEntity<Object>("test", HttpStatus.NOT_ACCEPTABLE);
}
@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundExceptions(Exception ex, WebRequest request) {
var exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<Object>(exceptionResponse, HttpStatus.NOT_FOUND);
}
}
我下面这个教程,如果它的任何帮助:https://www.baeldung.com/global-error-handler-in-a-spring-rest-api
1条答案
按热度按时间wwtsj6pe1#
如果您没有使用其他参数,请尝试以下操作