简体   繁体   English

来自 ResponseEntityExceptionHandler 的问题覆盖 handleMethodArgumentNotValid

[英]Problem override handleMethodArgumentNotValid from ResponseEntityExceptionHandler

I'm trying to override the handleMethodArgumentNotValid method but without success.我试图覆盖 handleMethodArgumentNotValid 方法但没有成功。

The error I'm getting is: "the method handleMethodArgumentNotValid(MethodArgumentNotValidException, HttpHeaders, HttpStatus, WebRequest) of type CustomResponseEntityExceptionHandler must override or implement a supertype but I don't know why I'm not doing it already.我得到的错误是:“CustomResponseEntityExceptionHandler 类型的方法 handleMethodArgumentNotValid(MethodArgumentNotValidException, HttpHeaders, HttpStatus, WebRequest) 必须覆盖或实现超类型,但我不知道为什么我还没有这样做。

Here's what I'm trying:这是我正在尝试的:

@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);
}

} }

I'm following this tutorial if it's any help: https://www.baeldung.com/global-error-handler-in-a-spring-rest-api如果有任何帮助,我会关注本教程: https://www.baeldung.com/global-error-handler-in-a-spring-rest-api

Well if you are not using other parameters try this好吧,如果你不使用其他参数,试试这个

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
    return new ResponseEntity<Object>("test", HttpStatus.NOT_ACCEPTABLE);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM