未调用 ResponseEntityExceptionHandler 的重写 handleMethodArgumentNotValid 方法

RTN*_*TN9 5 validation spring controller exception spring-boot

我正在尝试为我的 Spring Boot Rest 服务设置一个自定义验证器和一个 ExceptionHandler,当我添加 ExceptionHandler 时,验证错误没有发送到 UI。所以我试图覆盖 handleMethodArgumentNotValid 方法,但这也不起作用。有人可以对此有所了解吗?

这就是我在控制器中配置验证类的方式 -

package services.rest.controller;

import java.io.IOException;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;
import services.rest.model.TestInput;
import services.rest.validator.DataValidator;

@RestController
@RequestMapping("/test")
@Slf4j
public class RestResource {

    @Autowired
    private DataValidator validator;

    @PostMapping("/create")
    public String create(@Valid final TestInput input) throws IOException {
        log.debug(input.toString());
        return "Success";
    }

    @InitBinder()
    public void init(final WebDataBinder binder) {
        binder.addValidators(validator);
    }

}
Run Code Online (Sandbox Code Playgroud)

这是我的 ExceptionHandler 代码 -

package services.rest.exceptionhandler;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@SuppressWarnings({ "unchecked", "rawtypes" })
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllExceptions(final Exception ex, final WebRequest request) {
        System.out.println("All exceptions Method getting executed!!!!");

        final List<String> details = new ArrayList<>();
        details.add(ex.getLocalizedMessage());
        return new ResponseEntity("Server Error", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex,
            final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
        System.out.println("Validation Error Method getting executed!!!!");
        final List<String> details = new ArrayList<>();
        for (final ObjectError error : ex.getBindingResult().getAllErrors()) {
            details.add(error.getDefaultMessage());
        }
        return new ResponseEntity("Validation Error", HttpStatus.BAD_REQUEST);
    }
}
Run Code Online (Sandbox Code Playgroud)

最初没有覆盖“handleMethodArgumentNotValid”方法。现在也覆盖它后,它不起作用

小智 0

以下方法对我有用:

import java.util.ArrayList;
import java.util.List;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleAllExceptions(final Exception ex, final WebRequest request) {
        System.out.println("All exceptions Method getting executed!!!!");

        final List<String> details = new ArrayList<>();
        details.add(ex.getLocalizedMessage());
        return new ResponseEntity("Server Error", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    protected ResponseEntity<Object> handleMethodArgumentNotValid(final Exception ex, final WebRequest request) {
        System.out.println("Validation Error Method getting executed!!!!");
        final List<String> details = new ArrayList<>();
        details.add(ex.getLocalizedMessage());
        return new ResponseEntity("Validation Error", HttpStatus.BAD_REQUEST);
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上我所做的是:

  • 不延长ResponseEntityExceptionHandler课堂时间。
  • 放在@Order(Ordered.HIGHEST_PRECEDENCE)。
  • 为异常创建一个处理程序MissingServletRequestParameterException。

希望这对您有帮助