spring-boot-starter-validation数据校验全局异常拦截处理(转发)

原版参考:https://blog.csdn.net/tangyb828/article/details/126884417

特殊备注:简要整理笔记,非原著

一、引用Maven

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

二、使用拦截方式:

1、BindingResult对象接受和处理异常;
    @PostMapping("/taxinfoSearch")
    public Object taxinfoSearch(@Validated @RequestBody TaxRequestOrgInfo request, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            String messages = bindingResult.getAllErrors()
                    .stream()
                    .map(ObjectError::getDefaultMessage)
                    .reduce((m1, m2) -> m1 + "" + m2)
                    .orElse("参数输入有误!");
            return TaxOutResponse.loadResponseMsg(messages);
        }
        return orgInfoService.orgTaxInfoSearch(request).get(AjaxResult.DATA_TAG);
    }

 2、异常类拦截:

package dbgo.aei.qdtax;

import dbgo.aei.common.core.model.TaxOutResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * Description  validation拦截器
 * Author justin.jia
 * Date 2023/5/15 9:58
 **/
@Order(80)
@RestControllerAdvice
public class ValidationExceptionHandle {
    //日志文件
    public Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * BindException异常处理
     * <p>BindException: 作用于@Validated @Valid 注解,仅对于表单提交有效,对于以json格式提交将会失效</p>
     *
     * @param e BindException异常信息
     * @return 响应数据
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public TaxOutResponse bindExceptionHandler(BindException e) {
        String msg = e.getBindingResult().getFieldErrors()
                .stream()
                .map(n -> String.format("%s: %s", n.getField(), n.getDefaultMessage()))
                .reduce((x, y) -> String.format("%s; %s", x, y))
                .orElse("参数输入有误");

        logger.error("BindException异常,参数校验异常:{}", msg);
        return TaxOutResponse.loadResponseMsg(msg);
    }

    /**
     * MethodArgumentNotValidException-Spring封装的参数验证异常处理
     * <p>MethodArgumentNotValidException:作用于 @Validated @Valid 注解,接收参数加上@RequestBody注解(json格式)才会有这种异常。</p>
     *
     * @param e MethodArgumentNotValidException异常信息
     * @return 响应数据
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public TaxOutResponse methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult().getFieldErrors()
                .stream()
                .map(n -> String.format("%s: %s", n.getField(), n.getDefaultMessage()))
                .reduce((x, y) -> String.format("%s; %s", x, y))
                .orElse("参数输入有误");
        logger.error("MethodArgumentNotValidException异常,参数校验异常:{}", msg);
        return TaxOutResponse.loadResponseMsg(msg);
    }

    /**
     * ConstraintViolationException-jsr规范中的验证异常,嵌套检验问题
     * <p>ConstraintViolationException:作用于 @NotBlank @NotNull @NotEmpty 注解,校验单个String、Integer、Collection等参数异常处理。</p>
     * <p>注:Controller类上必须添加@Validated注解,否则接口单个参数校验无效</p>
     *
     * @param e ConstraintViolationException异常信息
     * @return 响应数据
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = ConstraintViolationException.class)
    public TaxOutResponse constraintViolationExceptionHandler(ConstraintViolationException e) {
        String msg = e.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining("; "));

        logger.error("ConstraintViolationException,参数校验异常:{}", msg);
        return TaxOutResponse.loadResponseMsg(msg);
    }
}

 

posted @ 2023-05-15 10:20  jiajinhao  阅读(498)  评论(0编辑  收藏  举报