@RestControllerAdvice原创
直接上代码,后面再说怎么用
1、这个是一个Form,用来接收参数的,一个简单的NotEmpty注解校验,merchantName这个参数是必传的;
package com.cloudwalk.shark.dto.validate;

import org.hibernate.validator.constraints.NotEmpty;

public class AdvertQueryForm {
@NotEmpty
private String merchantName; private String merchantCode; private String clientCode; private String id; public String getMerchantName() {
return merchantName;
} public void setMerchantName(String merchantName) {
this.merchantName = merchantName;
} public String getMerchantCode() {
return merchantCode;
} public void setMerchantCode(String merchantCode) {
this.merchantCode = merchantCode;
} public String getClientCode() {
return clientCode;
} public void setClientCode(String clientCode) {
this.clientCode = clientCode;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
}
}

2、Controller中直接通过RequestBody取到参数,下面是重点@Validated

这个注解可以直接用来校验传递的参数;

package com.cloudwalk.shark.controller;

import com.cloudwalk.shark.common.utils.ResponseData;
import com.cloudwalk.shark.dto.validate.AdvertQueryForm;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
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 org.springframework.web.bind.annotation.ResponseBody; @Controller
@RequestMapping(value = "/validate", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public class SharkValidationController { @PostMapping("/bean")
@ResponseBody
public ResponseData checkBeanIsValid(@Validated @RequestBody AdvertQueryForm advertQueryForm){
return new ResponseData(true,"2","3",advertQueryForm);
}
}

直接友好的捕获了你的参数校验异常,统一的去实现了参数异常的捕获!

重点!produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}这个参数如果不设定,默认返回的就会是XML;

package com.cloudwalk.shark.config.controllerException;

import com.cloudwalk.shark.common.em.GlobalCodeEnum;
import com.cloudwalk.shark.common.utils.ResponseData;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set; @RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ResponseData handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
StringBuilder errorInfo = new StringBuilder();
BindingResult bindingResult = exception.getBindingResult();
for(int i = 0; i < bindingResult.getFieldErrors().size(); i++){
if(i > 0){
errorInfo.append(",");
}
FieldError fieldError = bindingResult.getFieldErrors().get(i);
errorInfo.append(fieldError.getField()).append(" :").append(fieldError.getDefaultMessage());
} //返回BaseResponse
ResponseData response = new ResponseData();
response.setMessage(errorInfo.toString());
response.setCode(GlobalCodeEnum.FAIL.getErrorCode());
return response;
} @ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ResponseData<String> handleConstraintViolationException(ConstraintViolationException exception) {
StringBuilder errorInfo = new StringBuilder();
String errorMessage ; Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
for (ConstraintViolation<?> item : violations) {
errorInfo.append(item.getMessage()).append(",");
}
errorMessage = errorInfo.toString().substring(0, errorInfo.toString().length()-1); ResponseData<String> response = new ResponseData<String>();
response.setMessage(errorMessage);
response.setCode(GlobalCodeEnum.FAIL.getErrorCode());
return response;
} @ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseData<String> handleDefaultException(Exception exception) { ResponseData<String> response = new ResponseData<>();
response.setMessage("其他错误");
response.setCode(GlobalCodeEnum.FAIL.getErrorCode());
return response;
}
}

Validation(3)--全局参数异常校验捕获及返回XML解决的更多相关文章

  1. Spring 捕捉校验参数异常并统一处理

    使用 @Validated ,@Valid ,@NotBlank 之类的,请自行百度,本文着重与捕捉校验失败信息并封装返回出去 参考: https://mp.weixin.qq.com/s/EaZxY ...

  2. SpringBoot 全局异常拦截捕获处理

    一.全局异常处理 //Result定义全局数据返回对象 package com.xiaobing.demo001.domain; public class Result { private Integ ...

  3. (转)springboot全局处理异常(@ControllerAdvice + @ExceptionHandler)

    1.@ControllerAdvice 1.场景一 在构建RestFul的今天,我们一般会限定好返回数据的格式比如: { "code": 0, "data": ...

  4. Spring @ControllerAdvice @ExceptionHandler 全局处理异常

    对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚. 如此一来, ...

  5. 十四、springboot全局处理异常(@ControllerAdvice + @ExceptionHandler)

    1.@ControllerAdvice 1.场景一 在构建RestFul的今天,我们一般会限定好返回数据的格式比如: { "code": 0, "data": ...

  6. spring mvc 全局处理异常

    spring框架支持很多种全局处理异常的方式 一.Spring MVC处理异常有4种方式: (1)使用Spring-MVC提供的SimpleMappingExceptionResolver: (2)实 ...

  7. springmvc 全局的异常拦截处理 @ControllerAdvice注解 @ExceptionHandler

    第一步: Dispatcher前端控制器的源码中 默认的 private boolean throwExceptionIfNoHandlerFound = false;说明如果没有找到匹配的执行器,不 ...

  8. springboot之全局处理异常封装

    springboot之全局处理异常封装 简介 在项目中经常出现系统异常的情况,比如NullPointerException等等.如果默认未处理的情况下,springboot会响应默认的错误提示,这样对 ...

  9. WebApi安全性 参数签名校验(结合Axios使用)

    接口参数签名校验,是WebApi接口服务最重要的安全防护手段之一. 结合项目中实际使用情况,介绍下前后端参数签名校验实现方案. 签名校验规则 http请求,有两种传参形式: 1.通过url传参,最常见 ...

随机推荐

  1. r testifying that your code will behave as you intend.

    https://github.com/stretchr/testify Testify - Thou Shalt Write Tests    Go code (golang) set of pack ...

  2. r squared

    multiple r squared adjusted r squared http://web.maths.unsw.edu.au/~adelle/Garvan/Assays/GoodnessOfF ...

  3. Impala 安装笔记2一hive和mysql安装

    l   安装hive,hive-metastore hive-server $ sudo yum install hive hive-metastore hive-server l   安装mysql ...

  4. iOS 设备获取唯一标识符汇总

    在2013年3月21日苹果已经通知开发者,从2013年5月1日起,访问UIDID的应用将不再能通过审核,替代的方案是开发者应该使用“在iOS 6中介绍的Vendor或Advertising标示符”. ...

  5. src源dst目标

    dst是destination的缩写,表目的 src是source的缩写,表源

  6. kernel中对文件的读写【学习笔记】【原创】

    /*1. 头文件 */ #include <linux/init.h> #include <linux/module.h> #include <linux/modulep ...

  7. jquery特效(6)—判断复选框是否选中进行答题提示

    前面有一段时间思想开了小差,跟着师父学习了一段时间才发现差距很大,看来我要奋起直追~\(≧▽≦)/~啦啦啦. 最近公司在做一个项目,需要根据用户选择的选项给出相应的提示,下面来看我写的测试程序的效果: ...

  8. codeforces C. New Year Ratings Change 解题报告

    题目链接:http://codeforces.com/problemset/problem/379/C 题目意思:有n个users,每个user都有自己想升的rating.要解决的问题是给予每个人不同 ...

  9. 最新版ADT(Build: v22.6.2)总是引用appcompat_v7的问题

    昨天在ADT Manager里更新了一些组件,结果ADT不支持.索性直接下载了最新的ADT.但是发现无论创建什么类型的应用(无论支持的最低API是多少,或者是不是用模板),都会在创建应用的同时创建一个 ...

  10. JAVA通过信号量避免死锁

    死锁是这样一种情形:多个线程同时被阻塞,它们中的一个或者全部都在等待某个资源被释放.由于线程被无限期地阻塞,因此程序不可能正常终止. 导致死锁的根源在于不适当地运用"synchronized ...