@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

【记录】spring boot 全局捕获异常@ExceptionHandler与@Validated @RequestBody 配合使用的更多相关文章

  1. Spring Boot 全局异常配置

    Spring Boot 全局异常配置,处理异常控制器需要和发生异常的方法在一个类中.使用 ControllerAdvice 注解 package com.li.controller; import o ...

  2. Spring Boot全局异常处理

    本文为大家分享了Spring Boot全局异常处理,供大家参考,具体内容如下 1.后台处理异常 a.引入thymeleaf依赖 <!-- thymeleaf模板插件 --> <dep ...

  3. 记录Spring Boot大坑一个,在bean中如果有@Test单元测试,不会注入成功

    记录Spring Boot大坑一个,在bean中如果有@Test单元测试,不会注入成功 记录Spring Boot大坑一个,在bean中如果有@Test单元测试,不会注入成功 记录Spring Boo ...

  4. Spring Boot全局支持CORS(跨源请求)

    import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet. ...

  5. spring boot全局配置文件优先级

    前两篇介绍的application配置文件,即为spring boot全局配置文件.那么spring boot加载配置文件的时候,怎么确定加载哪个目录下哪个文件呢? spring boot默认的配置文 ...

  6. spring boot-11.全局捕获异常

    1.在Spring boot 中如果发生错误,浏览器访问会默认跳转到Whitelabel Error Page 这个错误页面,如果是客户端访问的话返回JSON格式的错误数据,说明spring boot ...

  7. Spring Boot 全局异常处理

    Spring Boot版本 1.5 @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExcept ...

  8. 使用 JSONDoc 记录 Spring Boot RESTful API

    这个博文可以分为两部分:第一部分我将编写一个Spring Boot RESTful API,第二部分将介绍如何使用JSONDoc来记录创建的API.做这两个部分最多需要15分钟,因为使用Spring ...

  9. Spring Boot 全局排除 spring-boot-starter-logging 依赖

    https://blog.csdn.net/u013314786/article/details/90412733 项目里使用了log4j2做日志处理,要排除掉Spring Boot 很多jar里边默 ...

随机推荐

  1. 软件安装——JRE多版本问题

    [Q]运行UMongo.exe文件时显示错误信息“The registry refers to a nonexsistent JAVA Runtime Envioroment or the Runti ...

  2. Acitiviti的查询及删除(六)

    流程定义查询 查询部署的流程定义. /** * 查询流程定义信息 //act_re_procdef */ public class QueryProcessDefinition { public st ...

  3. SQL读取表中不重复字段

    通关关键字 distinct 将AlbumName字段中所以不重复的内容读出来.

  4. bootstrap动态调用select下拉框

    html代码: <label for="classify" class="col-sm-2 control-label">填报部门:</lab ...

  5. 大数据笔记(三)——Hadoop2.0的安装与配置

    一.Hadoop安装部署的预备条件 准备:1.安装Linux和JDK. 安装JDK 解压:tar -zxvf jdk-8u144-linux-x64.tar.gz -C ~/training/ 设置环 ...

  6. 冲刺周六 Fighting SaturDay

    一.Saturday照片 二.项目分工 三.今日份燃尽图 四.项目进展 码云团队协同环境构建完毕 利用Leangoo制作任务分工及生成燃尽图 完成AES加解密部分代码 用代码实现对文件的新建.移动.复 ...

  7. 年薪100万的人都是怎么玩Excel的?

    年薪100万的人都是怎么玩Excel的? 2017-12-21 13:42美国 作者:珍妮Jenny 来源:一周进步(ID:weekweekup) 本文已获原作者转载授权,如需转载请联系原公号 本文重 ...

  8. The JavaScript this Keyword

    https://www.w3schools.com/js/js_this.asp What is this? The JavaScript this keyword refers to the obj ...

  9. React Native商城项目实战08 - 设置“More”界面cell

    1.自定义可复用的cell More/CommonCell.js: /** * 自定义可复用的cell */ import React, { Component } from 'react'; imp ...

  10. ajax工作原理,Jsonp原理

    Ajax工作原理是 相当于在用户和服务器之间加了-个中间层(AJAX引擎),使用户操作与服务器响应异步化. 对于用户请求ajax引擎会做一些数据验证和数据处理,不是所有请求都提交给服务器,当需要从服务 ...