当前位置:网站首页>如何使用 @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);
}
}
此时就会对 代码中的异常进行拦截 返回到前端,进行展示~
边栏推荐
- 整形和浮点型是如何在内存中的存储
- 【Transform】【NLP】首次提出Transformer,Google Brain团队2017年论文《Attention is all you need》
- 北京共有产权房出租新规实施的租赁案例
- Global and Chinese markets of AC electromechanical relays 2022-2028: Research Report on technology, participants, trends, market size and share
- The method of parameter estimation of user-defined function in MATLAB
- Puppet automatic operation and maintenance troubleshooting cases
- Yolov5 advanced 8 format conversion between high and low versions
- Kubernetes vous emmène du début à la fin
- 【Transform】【实践】使用Pytorch的torch.nn.MultiheadAttention来实现self-attention
- Jvm-04-runtime data area heap, method area
猜你喜欢
el-switch 赋值后状态不变化
Basic SQL tutorial
【注意力机制】【首篇ViT】DETR,End-to-End Object Detection with Transformers网络的主要组成是CNN和Transformer
[Yu Yue education] scientific computing and MATLAB language reference materials of Central South University
Functional modules and application scenarios covered by the productization of user portraits
Jvm-08-garbage collector
视觉上位系统设计开发(halcon-winform)-5.相机
视觉上位系统设计开发(halcon-winform)-3.图像控件
GCC cannot find the library file after specifying the link library path
What is machine reading comprehension? What are the applications? Finally someone made it clear
随机推荐
High quality workplace human beings must use software to recommend, and you certainly don't know the last one
【pytorch学习笔记】Datasets and Dataloaders
Redis cache penetration, cache breakdown, cache avalanche solution
视觉上位系统设计开发(halcon-winform)-6.节点与宫格
什么是embedding(把物体编码为一个低维稠密向量),pytorch中nn.Embedding原理及使用
Matlab r2011b neural network toolbox precautions
Win10 enterprise 2016 long term service activation tutorial
Final review points of human-computer interaction
Using TCL (tool command language) to manage Tornado (for VxWorks) can start the project
Characteristics of MySQL InnoDB storage engine -- Analysis of row lock
[daily training] 395 Longest substring with at least k repeated characters
Nppexec get process return code
Redis single thread problem forced sorting layman literacy
【Transform】【NLP】首次提出Transformer,Google Brain团队2017年论文《Attention is all you need》
Global and Chinese markets for flexible chips 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese markets for ionization equipment 2022-2028: Research Report on technology, participants, trends, market size and share
Qt常用语句备忘
Kubernetes vous emmène du début à la fin
Jvm-04-runtime data area heap, method area
Unity hierarchical bounding box AABB tree