@NotNull,@NotBlank使用及拦截配置

引入依赖

   <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.2.5.Final</version>
        </dependency>

在实体类中加入注解

 对应的参数使用类型

字符串使用@NotBlank

对象型基本类型是 @NotNull,数组是使用NotNull

集合型@NotEmpty

 在controller层加上@Valid开启效验

 开启返回前端的参数

这是一个最基本的普通返回做测试使用,实际项目中肯定是不行的,要有封装返回类,可以将String改成公司的封装返回类,

package com.sdk.controller.controller.qurzy;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.Servlet;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 替换掉blade框架RestExceptionTranslator的异常处理,不显示参数名称返回前端
 *
 * 全局异常处理
 * @author WQJ
 */
@Order(Integer.MIN_VALUE)
@Configuration
@ConditionalOnWebApplication(
        type = ConditionalOnWebApplication.Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class})
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    public GlobalExceptionHandler() {
        System.out.println("GlobalExceptionHandler init");
    }

    @ExceptionHandler({MissingServletRequestParameterException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleError(MissingServletRequestParameterException e) {
        log.info("GlobalExceptionHandler拦截器");
        String message = String.format("缺少必要的请求参数: %s", e.getParameterName());
        return message;
    }

    @ExceptionHandler({MethodArgumentTypeMismatchException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleError(MethodArgumentTypeMismatchException e) {
        log.info("GlobalExceptionHandler");
        String message = String.format("请求参数格式错误: %s", e.getName());
        return message;
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleError(MethodArgumentNotValidException e) {
        log.info("GlobalExceptionHandler");
        return this.handleError(e.getBindingResult());
    }

    @ExceptionHandler({BindException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleError(BindException e) {
        log.info("GlobalExceptionHandler");
        return this.handleError(e.getBindingResult());
    }

    private String handleError(BindingResult result) {
        FieldError error = result.getFieldError();
//        String message = String.format("%s:%s", error.getField(), error.getDefaultMessage());
        String message = String.format("%s", error.getDefaultMessage());
        return  message;
    }

    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleError(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = (ConstraintViolation)violations.iterator().next();
        String path = ((PathImpl)violation.getPropertyPath()).getLeafNode().getName();
        String message = String.format("%s:%s", path, violation.getMessage());
        return  message;
    }

    @ExceptionHandler({NoHandlerFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleError(NoHandlerFoundException e) {
        log.info("GlobalExceptionHandler");
        return e.getMessage();
    }

    @ExceptionHandler({HttpMessageNotReadableException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleError(HttpMessageNotReadableException e) {
        log.info("GlobalExceptionHandler");
        return e.getMessage();
    }

    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public String handleError(HttpRequestMethodNotSupportedException e) {
        log.info("GlobalExceptionHandler");
        return e.getMessage();
    }

    @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public String handleError(HttpMediaTypeNotSupportedException e) {
        log.info("GlobalExceptionHandler");
        return  e.getMessage();
    }

    @ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public String handleError(HttpMediaTypeNotAcceptableException e) {
        log.info("GlobalExceptionHandler");

        return e.getMessage();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值