【记录】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里边默 ...
随机推荐
- mysql INSERT语句 语法
mysql INSERT语句 语法 作用:用于向表格中插入新的行. 语法:INSERT INTO 表名称 VALUES (值1, 值2,....)或者INSERT INTO table_name (列 ...
- leetcode打卡
leetcode刷题打卡 刷题链接 夸夸群 刷题记录链接 期中颜色不一样的,是刷题中遇到问题的,以后需要强化 [x] 6.1 打卡 [x] 6.2 打卡 中间因个人原因没做题,后面慢慢补上 [x] 6 ...
- ARIMA模型--粒子群优化算法(PSO)和遗传算法(GA)
ARIMA模型(完整的Word文件可以去我的博客里面下载) ARIMA模型(英语:AutoregressiveIntegratedMovingAverage model),差分整合移动平均自回归模型, ...
- 特征提取算法(2)——HOG特征提取算法
histogram of oriented gradient(方向梯度直方图)特征是一种在计算机视觉和图像处理中用来进行物体检测的特征描述子.它通过计算和统计图像局部区域的梯度方向直方图来构成特征.H ...
- Redis 序列化方式StringRedisSerializer、FastJsonRedisSerializer和KryoRedisSerializer
当我们的数据存储到Redis的时候,我们的键(key)和值(value)都是通过Spring提供的Serializer序列化到数据库的.RedisTemplate默认使用的是JdkSerializat ...
- 关于scroll,client,innear,avail,offset等的理解
在写实例理解scrollWidth,clientWidth,innearWidth,availWidth及offsetWidth等的时候,意外的又发现了margin值合并的问题,在这里同时记录下 1. ...
- fedora18 Cannot retrieve metalink for repository: fedora. Please verify its path and try again 解决方法
Cannot retrieve metalink for repository: fedora. Please verify its path and try again 解决方法 执行如下命令: s ...
- apache cgi 程序: End of script output before headers
测试linux Apache cgi程序: #include <stdio.h> int main(){ printf("abc"); ; } 目录:/var/www/ ...
- C++编译-链接错误集合
1,无法解析的外部符号,链接错误,原因:没找到某个符号(变量或函数)的定义体,一般是对应函数没实现,或第三方库没有添加到工程设置中 2,重复链接链接错误,一个定义体(实现体)被多个CPPP文件包含,导 ...
- Python爬虫数据保存到MongoDB中
MongoDB是一款由C++语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容存储方式类似于JSON对象,它的字段值可以是其它文档或数组,但其数据类型只能是String文本型. ...