zoukankan      html  css  js  c++  java
  • spring boot请求参数验证

    场景:

    在接口中经常需要对参数的合法性做验证,spring boot中提供了@Vaild注解,可以方便的完成验证。如何处理验证失败的返回类型,方便客户端调用。

    解决思路:

    在验证参数失败时,会抛出一个MethodArgumentNotValidException的异常,如果我们能捕获这个异常,那就可以把异常信息返回给客户端。

    我们可以使用@RestControllerAdvice注解,对我们的Controller增强,捕获MethodArgumentNotValidException、HttpMessageNotReadableException以及我们自定义的ParamaErrorException。

    实现:

    @RestControllerAdvice("net.kisssoft.controllers")
    public class ControllerExceptionAdvice {
    
        /**
         * 忽略参数异常处理器
         *
         * @param e 忽略参数异常
         * @return ResponseResult
         */
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ExceptionHandler(MissingServletRequestParameterException.class)
        public Result parameterMissingExceptionHandler(MissingServletRequestParameterException e) {
            return Result.CreateFail("请求参数 " + e.getParameterName() + " 不能为空");
        }
    
        /**
         * 缺少请求体异常处理器
         *
         * @param e 缺少请求体异常
         * @return ResponseResult
         */
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ExceptionHandler(HttpMessageNotReadableException.class)
        public Result parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) {
            return Result.CreateFail("参数体不能为空");
        }
    
        /**
         * 参数效验异常处理器
         *
         * @param e 参数验证异常
         * @return ResponseInfo
         */
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ExceptionHandler(MethodArgumentNotValidException.class)
        public Result parameterExceptionHandler(MethodArgumentNotValidException e) {
            BindingResult exceptions = e.getBindingResult();
            // 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息
            if (exceptions.hasErrors()) {
                List<ObjectError> errors = exceptions.getAllErrors();
                if (!errors.isEmpty()) {
                    // 这里列出了全部错误参数,按正常逻辑,只需要第一条错误即可
                    FieldError fieldError = (FieldError) errors.get(0);
                    return Result.CreateFail(fieldError.getDefaultMessage());
                }
            }
            return Result.CreateFail("error");
        }
    
        /**
         * 自定义参数错误异常处理器
         *
         * @param e 自定义参数
         * @return ResponseInfo
         */
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ExceptionHandler({ParamaErrorException.class})
        public Result paramExceptionHandler(ParamaErrorException e) {
            //log.error("", e);
            // 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息
            if (!StringUtils.isEmpty(e.getMessage())) {
                return Result.CreateFail(e.getMessage());
            }
            return Result.CreateFail("error");
        }
    
    }


    Result是我们通用的返回类型,当参数验证失败,我们返回400。并返回对应的类型。


  • 相关阅读:
    leetcode 268. Missing Number
    DBSCAN
    python二维数组初始化
    leetcode 661. Image Smoother
    leetcode 599. Minimum Index Sum of Two Lists
    Python中的sort() key含义
    leetcode 447. Number of Boomerangs
    leetcode 697. Degree of an Array
    滴滴快车奖励政策,高峰奖励,翻倍奖励,按成交率,指派单数分级(1月3日)
    北京Uber优步司机奖励政策(1月2日)
  • 原文地址:https://www.cnblogs.com/wugang/p/14232348.html
Copyright © 2011-2022 走看看