spring 从响应实体异常处理程序重写handleMethodArgumentNotValid时出现问题

ztyzrc3y  于 2023-02-11  发布在  Spring
关注(0)|答案(1)|浏览(128)

我尝试重写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

wwtsj6pe

wwtsj6pe1#

如果您没有使用其他参数,请尝试以下操作

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

相关问题