全局参数校验

1 pom.xml引入依赖

<!--参数校验-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2 get请求

/**
 * test
 *
 * @author gaorimao
 * @since 2021-04-29
 */
@RestController
@Validated
public class TestController {
    /**
     * get请求,拼在路径上的参数校验,需要在控制器上添加@Validated注解
     */
    @GetMapping("/test/get/params")
    public Result testUsername(@Length(min = 4) @RequestParam("username") String username,
                               @Length(max = 4) @RequestParam("password") String password) {
        return Result.success();
    }
}

3 POST请求

/**
 * 将校验结果放进BindingResult里面,用户自行判断并处理
 */
@PostMapping(value = "/test/params", produces = "application/json;charset=UTF-8")
public Result testBindingResult(@RequestBody @Valid LoginRequest loginRequest) {
    return Result.success();
}

请求体注解

import lombok.Data;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;


@Data
public class LoginRequest {
    @NotBlank(message = "用户名不能为空!")
    @Min(value = 5)
    private String username;
    @NotBlank(message = "密码不能为空!")
    private String password;
}

4 全局自定义异常捕获

import com.grm.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
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.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.StringJoiner;

/**
 * 自定义全局异常捕获
 *
 * @author gaorimao
 */
@RestControllerAdvice(annotations = RestController.class)
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 全局异常捕捉处理
     *
     * @param e 异常
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(HttpServletRequest req, Exception e) {
        return Result.failed(500, e.getMessage());
    }

    /**
     * 全局异常捕捉处理
     *
     * @param e 异常
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public Result businessExceptionHandler(HttpServletRequest req, Exception e) {
        return Result.failed(500, e.getMessage());
    }

    /**
     * post请求body体参数校验,异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("[exception] methodArgumentNotValidException error : {}",e);
        // 将所有的错误提示使用";"拼接起来并返回
        StringJoiner sj = new StringJoiner(";");
        //name:不能为空;password:长度不能小于4
        e.getBindingResult().getFieldErrors().forEach(x -> sj.add(x.getField()+":"+x.getDefaultMessage()));
        return Result.failed(500, sj.toString());
    }

    /**
     * 缺少body请求体异常处理器
     *
     * @param e 缺少请求体异常
     * @return ResponseResult
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) {
        return Result.failed(500, "body请求体不能为空!");
    }

    /**
     * 忽略参数异常处理器
     *
     * @param e 忽略参数异常
     * @return ResponseResult
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result parameterMissingExceptionHandler(MissingServletRequestParameterException e) {
        return Result.failed(500, "请求参数"+e.getParameterName()+"不能为空!");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值