【记录】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
【记录】spring boot 全局捕获异常@ExceptionHandler与@Validated @RequestBody 配合使用的更多相关文章
- Spring Boot 全局异常配置
Spring Boot 全局异常配置,处理异常控制器需要和发生异常的方法在一个类中.使用 ControllerAdvice 注解 package com.li.controller; import o ...
- Spring Boot全局异常处理
本文为大家分享了Spring Boot全局异常处理,供大家参考,具体内容如下 1.后台处理异常 a.引入thymeleaf依赖 <!-- thymeleaf模板插件 --> <dep ...
- 记录Spring Boot大坑一个,在bean中如果有@Test单元测试,不会注入成功
记录Spring Boot大坑一个,在bean中如果有@Test单元测试,不会注入成功 记录Spring Boot大坑一个,在bean中如果有@Test单元测试,不会注入成功 记录Spring Boo ...
- Spring Boot全局支持CORS(跨源请求)
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet. ...
- spring boot全局配置文件优先级
前两篇介绍的application配置文件,即为spring boot全局配置文件.那么spring boot加载配置文件的时候,怎么确定加载哪个目录下哪个文件呢? spring boot默认的配置文 ...
- spring boot-11.全局捕获异常
1.在Spring boot 中如果发生错误,浏览器访问会默认跳转到Whitelabel Error Page 这个错误页面,如果是客户端访问的话返回JSON格式的错误数据,说明spring boot ...
- Spring Boot 全局异常处理
Spring Boot版本 1.5 @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExcept ...
- 使用 JSONDoc 记录 Spring Boot RESTful API
这个博文可以分为两部分:第一部分我将编写一个Spring Boot RESTful API,第二部分将介绍如何使用JSONDoc来记录创建的API.做这两个部分最多需要15分钟,因为使用Spring ...
- Spring Boot 全局排除 spring-boot-starter-logging 依赖
https://blog.csdn.net/u013314786/article/details/90412733 项目里使用了log4j2做日志处理,要排除掉Spring Boot 很多jar里边默 ...
随机推荐
- 【PowerOJ1742&网络流24题】试题库问题(最大流)
题意: 思路: [问题分析] 二分图多重匹配问题,用最大流解决. [建模方法] 建立二分图,每个类别为X集合中的顶点,每个题为Y集合中的顶点,增设附加源S和汇T. 1.从S向每个Xi连接一条容量为该类 ...
- CF1081G Mergesort Strikes Back
题目大意: 给定\(n\),\(k\),\(mod\),求随机排列在\(k\)层归并排序下逆序对的期望. 题解 考虑这\(k\)层归并会把序列分成若干个块. 这些块内的顺序是原序列的相对顺序,我们要把 ...
- CG-CTF | 密码重置2
跟则提示走,美滋滋: 1.找到邮箱: 2.下载备份: 3.PHP弱类型,string与int用的是“==” ........这一行是省略的代码........ if(!empty($token)&am ...
- [CSP-S模拟测试]:matrix(DP)
题目描述 求出满足以下条件的$n\times m$的$01$矩阵个数:(1)第$i$行第$1~l_i$列恰好有$1$个$1$.(2)第$i$行第$r_i~m$列恰好有$1$个$1$.(3)每列至多有$ ...
- 数据库-SqlServer 行转列,列转行
两篇行转列,列转行的实例文章: 第1篇:https://www.cnblogs.com/cpcpc/archive/2013/04/08/3009021.html 第2篇:https://mp.wei ...
- 2019 Nanchang Onsite
D.Interesting Series F(n)实际上是一个等比数列的和,将它从递推式转变为通项公式(a^n-1)/(a-1),这里只需要确定n就可以. 题目要求选取k大小的所有子集的答案求和,可以 ...
- nginx的域名解析
1.创建域名解析结构: ngx_resolver_create(ngx_conf_t *cf, ngx_str_t *names, ngx_uint_t n) 这里面的names是dns服务器的地址 ...
- 阶段1 语言基础+高级_1-3-Java语言高级_1-常用API_1_第4节 ArrayList集合_14-ArrayList集合的常用方法和循环
常用的方法记下来 刚创建好,什么都不放的 add添加方法肯定是成功的. 加了这么多的值都没有用返回值,输出的结果可以看到都是添加成功的 获取索引值 ALT+回车键,推荐使用本地变量去接收 这样左边就会 ...
- android window(四)WindowToken
在WindowManagerService中有两种常见的Token,WindowToken,和AppWindowToken. WindowToken http://androidxref.com/6. ...
- How to use Nlog for ASP.NET Core with csproj
1. Add dependency in csproj manually or using NuGet Install the latest: NLog.Web.AspNetCore 4.5+ Upd ...