获取为MethodArgumentNotValidExcepti

获取为MethodArgumentNotValidExcepti

本文介绍了在春季启动应用程序启动时获取为MethodArgumentNotValidException映射的模糊@ExceptionHandler方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的一个spring控制器编写了自定义异常处理程序类,以验证来自请求参数的email属性是否采用正确的格式.因此,创建了一个扩展 ResponseEntityExceptionHandler 类的新类,并使用 @ExceptionHandler 编写了一个方法.

I have written custom exception handler class for one of my spring controllers to validate if email attribute from request param is in the proper format. So created a new class which extends ResponseEntityExceptionHandler class and wrote a method with @ExceptionHandler.

但是在春季启动应用程序启动期间,我遇到了以下异常,该异常正在停止运行我的项目.有人可以帮我解决这个问题吗?

But during spring boot application startup, I am getting below exception which is stopping to run my project. Could someone help me to resolve this?

服务器启动期间的异常:

用于处理 MethodArgumentNotValidException 的自定义类:

@ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorVO processValidationError(MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();
        FieldError fieldError = fieldErrors.get(0);
        ErrorVO dto = new ErrorVO(fieldError.getDefaultMessage());
        return dto;
    }
}

推荐答案

含糊不清是因为您在两个类中都具有相同的方法-@ExceptionHandler-ResponseEntityExceptionHandler,MethodArgumentNotValidException.您需要按如下所示编写重写的方法来解决此问题-

The ambiguity is because you have the same method - @ExceptionHandler in both the classes - ResponseEntityExceptionHandler, MethodArgumentNotValidException. You need to write the overridden method as follows to get around this issue -

   @Override
   protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                 HttpHeaders headers, HttpStatus status, WebRequest request) {
          String errorMessage = ex.getBindingResult().getFieldErrors().get(0).getDefaultMessage();
          List<String> validationList = ex.getBindingResult().getFieldErrors().stream().map(fieldError->fieldError.getDefaultMessage()).collect(Collectors.toList());
          LOGGER.info("Validation error list : "+validationList);
          ApiErrorVO apiErrorVO = new ApiErrorVO(errorMessage);
          apiErrorVO.setErrorList(validationList);
          return new ResponseEntity<>(apiErrorVO, status);
   }

这篇关于在春季启动应用程序启动时获取为MethodArgumentNotValidException映射的模糊@ExceptionHandler方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 05:04