当前位置:网站首页>如何使用 @NotNull等注解校验 并全局异常处理
如何使用 @NotNull等注解校验 并全局异常处理
2022-07-03 15:18:00 【ジ你是我永远のbugグ】
@NotNul 等注解的使用
代码:码云
1、添加依赖
<!-- validation组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2、在 controller 请求参数前 + @Vaild
@RequestMapping("/doLogin")
@ResponseBody
public RespBean doLogin(@Valid LoginRequestParam param){
}
3、在参数实体类上 加注解
@Data
public class LoginRequestParam {
@NotBlank(message = "mobile不能为空")
@IsMobile
private String mobile;
@NotBlank(message = "password不能为空")
@Length(min = 32,message = "password 长度不对")
private String password;
}
此时 的异常不会在页面显示 而是会 报400错误,并在 后台打印出错误,这就需要对异常进行拦截
后台保错信息,可知 注解拦截的异常为 BindException
Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'loginRequestParam' on field 'mobile': rejected value [11]; codes [IsMobile.loginRequestParam.mobile,IsMobile.mobile,IsMobile.java.lang.String,IsMobile]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [loginRequestParam.mobile,mobile]; arguments []; default message [mobile],true]; default message [手机号码 格式错误]]
全局异常处理
1、 首先 定义 异常的枚举信息
package com.example.seckill.common;
/** * 公共返回对象枚举 * * @author: LC * @date 2022/3/2 1:44 下午 * @ClassName: RespBean */
public enum RespBeanEnum {
//通用
SUCCESS(200, "SUCCESS"),
ERROR(500, "服务端异常"),
//登录模块
LOGIN_ERROR(500210, "用户名或者密码不正确"),
MOBILE_ERROR(500211, "手机号码格式不正确"),
BIND_ERROR(500212, "参数校验异常"),
MOBILE_NOT_EXIST(500213, "手机号码不存在"),
PASSWORD_UPDATE_FAIL(500214, "更新密码失败"),
SESSION_ERROR(500215, "用户SESSION不存在"),
//秒杀模块
EMPTY_STOCK(500500, "库存不足"),
REPEATE_ERROR(500501, "该商品每人限购一件"),
REQUEST_ILLEGAL(500502, "请求非法,请重新尝试"),
ERROR_CAPTCHA(500503, "验证码错误,请重新输入"),
ACCESS_LIMIT_REACHED(500504, "访问过于频繁,请稍后重试"),
//订单模块5003xx
ORDER_NOT_EXIST(500300, "订单不存在"),
;
private final Integer code;
private final String message;
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
RespBeanEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
}
2、 定义 返回信息的格式
package com.example.seckill.common;
/** * 公共返回对象 * * @author: LC * @date 2022/3/2 1:50 下午 * @ClassName: RespBean */
public class RespBean {
private long code;
private String message;
private Object object;
public static RespBean success() {
return new RespBean(RespBeanEnum.SUCCESS.getCode(), RespBeanEnum.SUCCESS.getMessage(), null);
}
public static RespBean success(Object object) {
return new RespBean(RespBeanEnum.SUCCESS.getCode(), RespBeanEnum.SUCCESS.getMessage(), object);
}
public static RespBean error(RespBeanEnum respBeanEnum) {
return new RespBean(respBeanEnum.getCode(), respBeanEnum.getMessage(), null);
}
public static RespBean error(RespBeanEnum respBeanEnum, Object object) {
return new RespBean(respBeanEnum.getCode(), respBeanEnum.getMessage(), object);
}
public RespBean(long code, String message, Object object) {
this.code = code;
this.message = message;
this.object = object;
}
public RespBean() {
}
public long getCode() {
return code;
}
public void setCode(long code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
3、 定义 全局异常处理类
package com.example.seckill.exception;
import com.example.seckill.common.RespBeanEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/** * * 全局异常 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GlobalException extends RuntimeException{
RespBeanEnum respBeanEnum;
}
4、 定义 异常拦截器
package com.example.seckill.exception;
import com.example.seckill.common.RespBean;
import com.example.seckill.common.RespBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/** * 全局异常拦截器 * */
@RestControllerAdvice
public class GlobalExceptionHandle {
// 异常拦截
@ExceptionHandler(Exception.class)
public RespBean ExceptionHandler(Exception e){
if (e instanceof GlobalException){
// 如果拦截的异常是我们定义的异常 则直接return
GlobalException ex = (GlobalException) e;
return RespBean.error(ex.getRespBeanEnum());
}else if (e instanceof BindException){
// 如果是注解拦截的异常 绑定异常
BindException e1 = (BindException) e;
RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
respBean.setMessage("参数检验异常" + e1.getBindingResult().getAllErrors().get(0).getDefaultMessage()); //显示 具体错误信息
return respBean;
}
return RespBean.error(RespBeanEnum.ERROR);
}
}
此时就会对 代码中的异常进行拦截 返回到前端,进行展示~
边栏推荐
- GCC cannot find the library file after specifying the link library path
- Zero copy underlying analysis
- redis缓存穿透,缓存击穿,缓存雪崩解决方案
- Using Tengine to solve the session problem of load balancing
- Kubernetes带你从头到尾捋一遍
- Global and Chinese market of postal automation systems 2022-2028: Research Report on technology, participants, trends, market size and share
- Nppexec get process return code
- Functional modules and application scenarios covered by the productization of user portraits
- Using notepad++ to build an arbitrary language development environment
- Using TCL (tool command language) to manage Tornado (for VxWorks) can start the project
猜你喜欢
Jvm-08-garbage collector
求字符串函数和长度不受限制的字符串函数的详解
C语言刷题~Leetcode与牛客网简单题
Série yolov5 (i) - - netron, un outil de visualisation de réseau
Jvm-05-object, direct memory, string constant pool
"Seven weapons" in the "treasure chest" of machine learning: Zhou Zhihua leads the publication of the new book "machine learning theory guide"
【注意力机制】【首篇ViT】DETR,End-to-End Object Detection with Transformers网络的主要组成是CNN和Transformer
基础SQL教程
函数栈帧的创建和销毁
What is machine reading comprehension? What are the applications? Finally someone made it clear
随机推荐
[combinatorics] permutation and combination (set permutation, step-by-step processing example)
[attention mechanism] [first vit] Detr, end to end object detection with transformers the main components of the network are CNN and transformer
redis缓存穿透,缓存击穿,缓存雪崩解决方案
Leasing cases of the implementation of the new regulations on the rental of jointly owned houses in Beijing
Search in the two-dimensional array of leetcode sword offer (10)
Analysis of development mode process based on SVN branch
Jvm-06-execution engine
"Seven weapons" in the "treasure chest" of machine learning: Zhou Zhihua leads the publication of the new book "machine learning theory guide"
视觉上位系统设计开发(halcon-winform)-4.通信管理
北京共有产权房出租新规实施的租赁案例
求字符串函数和长度不受限制的字符串函数的详解
Yolov5系列(一)——網絡可視化工具netron
【可能是全中文网最全】pushgateway入门笔记
Idea does not specify an output path for the module
使用JMeter对WebService进行压力测试
Redis lock Optimization Practice issued by gaobingfa
Matlab r2011b neural network toolbox precautions
使用Tengine解决负载均衡的Session问题
Kubernetes - yaml file interpretation
视觉上位系统设计开发(halcon-winform)-3.图像控件