• 个人博客开发之blogapi项目统一全局异常处理和参数验证


    前言

    项目开发中异常捕获,抛出,记录,也是非常重要的,便于我们以后项目bug定位追踪,

    Hibernate Validator 参数校验

    通过整合spring-boot-starter-validation进行全局参数校验

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

    具体使用请参考我这两篇文章

    SpringBoot Validation优雅的全局参数校验

    SpringBoot Validation详解自定校验和分组校验

    全局异常捕获GlobalExceptionHandler

    package cn.soboys.core;
    
    import cn.hutool.core.collection.CollectionUtil;
    import cn.hutool.core.util.StrUtil;
    import cn.soboys.core.authentication.AuthenticationException;
    import cn.soboys.core.ret.Result;
    import cn.soboys.core.ret.ResultCode;
    import cn.soboys.core.ret.ResultResponse;
    import org.springframework.validation.BindException;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.FieldError;
    import org.springframework.web.HttpMediaTypeNotSupportedException;
    import org.springframework.web.HttpRequestMethodNotSupportedException;
    import org.springframework.web.bind.MethodArgumentNotValidException;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RestControllerAdvice;
    import org.springframework.web.servlet.NoHandlerFoundException;
    
    import javax.validation.ConstraintViolation;
    import javax.validation.ConstraintViolationException;
    import javax.validation.Path;
    import java.util.List;
    import java.util.Set;
    import java.util.stream.Collectors;
    
    /**
     * @author kenx
     * @version 1.0
     * @date 2021/6/17 20:19
     * 全局异常统一处理
     */
    @RestControllerAdvice
    public class GlobalExceptionHandler {
    
        /**
         * 处理 json 请求体调用接口对象参数校验失败抛出的异常
         */
        @ExceptionHandler(MethodArgumentNotValidException.class)
        public Result jsonParamsException(MethodArgumentNotValidException e) {
            BindingResult bindingResult = e.getBindingResult();
            List errorList = CollectionUtil.newArrayList();
    
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                String msg = String.format("%s%s;", fieldError.getField(), fieldError.getDefaultMessage());
                errorList.add(msg);
            }
            return ResultResponse.failure(ResultCode.PARAMS_IS_INVALID, errorList);
        }
    
    
        /**
         * 处理单个参数校验失败抛出的异常
         */
        @ExceptionHandler(ConstraintViolationException.class)
        public Result ParamsException(ConstraintViolationException e) {
    
            List errorList = CollectionUtil.newArrayList();
            Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
            for (ConstraintViolation<?> violation : violations) {
                StringBuilder message = new StringBuilder();
                Path path = violation.getPropertyPath();
                String[] pathArr = StrUtil.splitToArray(path.toString(), ".");
                String msg = message.append(pathArr[1]).append(violation.getMessage()).toString();
                errorList.add(msg);
            }
            return ResultResponse.failure(ResultCode.PARAMS_IS_INVALID, errorList);
        }
    
        /**
         * @param e
         * @return 处理 form data方式调用接口对象参数校验失败抛出的异常
         */
        @ExceptionHandler(BindException.class)
        public Result formDaraParamsException(BindException e) {
            List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
            List<String> collect = fieldErrors.stream()
                    .map(o -> o.getField() + o.getDefaultMessage())
                    .collect(Collectors.toList());
            return ResultResponse.failure(ResultCode.PARAMS_IS_INVALID, collect);
        }
    
        /**
         * 请求方法不被允许异常
         */
        @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
        public Result httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
            return ResultResponse.failure(ResultCode.METHOD_NOT_ALLOWED);
        }
    
        /**
         * @param e
         * @return Content-Type/Accept 异常
         * application/json
         * application/x-www-form-urlencoded
         */
        @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
        public Result httpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
            return ResultResponse.failure(ResultCode.BAD_REQUEST);
        }
    
        /**
         * handlerMapping  接口不存在跑出异常
         *
         * @param e
         * @return
         */
        @ExceptionHandler(NoHandlerFoundException.class)
        public Result noHandlerFoundException(NoHandlerFoundException e) {
            return ResultResponse.failure(ResultCode.NOT_FOUND, e.getMessage());
        }
    
    
        /**
         * 认证异常
         * @param e
         * @return
         */
        @ExceptionHandler(AuthenticationException.class)
        public Result UnNoException(AuthenticationException e) {
            return ResultResponse.failure(ResultCode.UNAUTHORIZED,e.getMessage());
        }
    
        /**
         *
         * @param e 未知异常捕获
         * @return
         */
        @ExceptionHandler(Exception.class)
        public Result UnNoException(Exception e) {
            return ResultResponse.failure(ResultCode.INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    

    具体详细使用请参考我这篇文章 SpringBoot优雅的全局异常处理

    关注公众号猿小叔获取更多干货分享

  • 相关阅读:
    Openjudge-计算概论(A)-单词翻转
    Openjudge-计算概论(A)-字符串排序
    Openjudge-计算概论(A)-过滤多余的空格
    Openjudge-计算概论(A)-单词倒排
    Openjudge-计算概论(A)-统计字符数
    Openjudge-计算概论(A)-奇数单增序列
    碎碎的光阴(湖北荆门一考生)
    Openjudge-计算概论(A)-找和为K的两个元素
    php延迟加载的示例
    php排序测试
  • 原文地址:https://www.cnblogs.com/kenx/p/15028737.html
Copyright © 2020-2023  润新知