• 【记录】spring boot 全局捕获异常@ExceptionHandler与@Validated @RequestBody 配合使用


      

      @ExceptionHandler与@Validated @RequestBody 三者配合使用可以很好的做到入参校验,具体demo如下:

    接口

    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import com.xx.common.core.CommonResult;
    import com.xx.product.input.dto.ProductDetailCollectParam;
    
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    
    @Api(tags = "商品详情页接口")
    @RequestMapping(value = "/product")
    public interface ProductDetailService {
    
    	@PostMapping("/collect")
    	@ApiOperation(value = "收藏商品接口")
    	public CommonResult collectProduct(@RequestBody @Validated ProductDetailCollectParam productDetailCollectParam);
    	
    }
    

      

    入参类

    import javax.validation.constraints.NotBlank;
    
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    
    @Data
    @ApiModel(value = "商品详情页入参")
    public class ProductDetailCollectParam {
    
        @NotBlank(message = "用户openid不能为空")
        @ApiModelProperty(value = "用户openid")
        private String openid;
        
        @NotBlank(message = "商品id不能为空")
        @ApiModelProperty(value = "商品id")
        private String id;
    }
    

      

    全局捕获异常类

    import org.springframework.web.bind.annotation.RestControllerAdvice;
    import java.util.List;
    import javax.validation.ConstraintViolationException;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.FieldError;
    import org.springframework.web.bind.MethodArgumentNotValidException;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import com.xx.common.core.CommonResult;
    
    import cn.hutool.core.util.StrUtil;
    import lombok.extern.slf4j.Slf4j;
    
    @Slf4j
    @RestControllerAdvice
    public class GlobalExecptionHandler {
    
        /**
         * 全局异常拦截
         * @param e
         * @return
         */
        @ExceptionHandler(Exception.class)
        public CommonResult handler(Exception exception) {
            
            StringBuilder errMsg = new StringBuilder();
            // 方法参数无效 异常
            if(exception instanceof MethodArgumentNotValidException) {
               BindingResult  bindResult = ((MethodArgumentNotValidException) exception).getBindingResult();
               List<FieldError> fieldErrorList = bindResult.getFieldErrors();
                fieldErrorList.forEach(fieldErrors -> {
                    FieldError fieldError = fieldErrors;
                    if (StrUtil.isNotBlank(errMsg.toString())) {
                        errMsg.append(",");
                    }
                    errMsg.append(fieldError.getDefaultMessage());
                }
               );
               
            }else if (exception instanceof ConstraintViolationException) {
                // 约束冲突异常
                
            }
    //        log.error("异常:",exception);
            return CommonResult.failed(errMsg.toString());
        }
    

      

    参考链接:https://www.cnblogs.com/cjyboy/p/11465876.html

    参考链接:https://blog.csdn.net/lzhcoder/article/details/98870852

  • 相关阅读:
    积累-T
    HTML:文件标签(四)
    HTML:文件标签(三)
    HTML:文件标签(二)
    队列:最近的请求次数 (Leetcode 933 / Leetcode 232 / 剑指09 / Leetcode 225 / Leetcode 862 )
    HTML:文件标签(一)
    HTML: 介绍 & 规范
    java.sql.SQLException: Access denied for user 'root '@'localhost' (using password: YES)
    JDBC和XML- 学习笔记
    数据库: 商城案例
  • 原文地址:https://www.cnblogs.com/wbl001/p/11935636.html
Copyright © 2020-2023  润新知