@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. php中如何上传整个文件夹里的所有文件?

    1.使用PHP的创始人 Rasmus Lerdorf 写的APC扩展模块来实现(http://pecl.php.net/package/apc) APC实现方法: 安装APC,参照官方文档安装,可以使 ...

  2. HDU 4348 SPOJ 11470 To the moon

    Vjudge题面 Time limit 2000 ms Memory limit 65536 kB OS Windows Source 2012 Multi-University Training C ...

  3. python 指定画图分辨率

    from IPython.core.pylabtools import figsize # import figsize figsize(12.5, 4) # 设置 figsize plt.rcPar ...

  4. Vue中的MVVM框架

    ViewModel:数据双向绑定 场景: 针对具有复杂交互逻辑的前段应用 提供基础的架构抽象 通过Ajax数据持久化,保证前端用户体验  什么是vue.js? 是一个轻量级的mvvm框架 数据驱动+组 ...

  5. Linux shell -查找字符(find,xargs,grep)

    在当前目录下查找含有jmxremote字符的文件 test@>find . -type f|xargs grep "jmxremote" . 当前目录 -type 查找文件类 ...

  6. percona-toolkit 工具介绍

    percona-toolkit 工具介绍 percona-toolkit 是一组高级命令行工具的集合,用来执行各种通过手工执行非常复杂和麻烦的mysql和系统任务.这些任务包括: 检查master和s ...

  7. ASP Loading

    ASP 页面加载等待效果.如 显示"请稍后页面正在加载...",加载完成后隐藏这个loading. <%Response.buffer=false%> <html ...

  8. ReentrantLock 源码分析

    ReentrantLock 1)ReentrantLock 类实现了和 synchronized 一样的内存语义,同时该类提供了更加灵活多样的可重入互斥锁定操作. 2)ReentrantLock 实例 ...

  9. 在mpvue或者Vue中使用VUEX

    第一个页面Index,主页哦 import Vue from'vue' import Vuex from'vuex' import getters from'./getters' import sta ...

  10. Helvetic Coding Contest 2019 online mirror (teams allowed, unrated)

    http://codeforces.com/contest/1184 A1 找一对整数,使x^x+2xy+x+1=r 变换成一个分式,保证整除 #include<iostream> #in ...