当前位置:网站首页>如何使用 @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);
}
}
此时就会对 代码中的异常进行拦截 返回到前端,进行展示~
边栏推荐
- Solve the problem that pushgateway data will be overwritten by multiple push
- Didi off the shelf! Data security is national security
- App全局异常捕获
- socket. IO build distributed web push server
- Yolov5 advanced seven target tracking latest environment construction (II)
- [probably the most complete in Chinese] pushgateway entry notes
- [cloud native training camp] module 7 kubernetes control plane component: scheduler and controller
- [pytorch learning notes] datasets and dataloaders
- Kubernetes - yaml file interpretation
- Kubernetes带你从头到尾捋一遍
猜你喜欢

【可能是全中文网最全】pushgateway入门笔记

北京共有产权房出租新规实施的租赁案例

Zero copy underlying analysis
![[cloud native training camp] module 7 kubernetes control plane component: scheduler and controller](/img/a4/2156b61fbf50db65fdf59c8f5538f8.png)
[cloud native training camp] module 7 kubernetes control plane component: scheduler and controller

Finally, someone explained the financial risk management clearly

视觉上位系统设计开发(halcon-winform)

Unity hierarchical bounding box AABB tree

什么是one-hot encoding?Pytorch中,将label变成one hot编码的两种方式

【Transform】【NLP】首次提出Transformer,Google Brain团队2017年论文《Attention is all you need》

Solve the problem that pushgateway data will be overwritten by multiple push
随机推荐
Detailed comments on MapReduce instance code on the official website
Puppet automatic operation and maintenance troubleshooting cases
[pytorch learning notes] datasets and dataloaders
Qt常用语句备忘
Incluxdb2 buckets create database
Relationship between truncated random distribution and original distribution
Halcon与Winform学习第一节
el-switch 赋值后状态不变化
Halcon与Winform学习第二节
PyTorch crop images differentiablly
Dataframe returns the whole row according to the value
socket. IO build distributed web push server
Jvm-08-garbage collector
视觉上位系统设计开发(halcon-winform)
Jvm-09 byte code introduction
Zero copy underlying analysis
The state does not change after the assignment of El switch
求字符串函数和长度不受限制的字符串函数的详解
详解指针进阶1
Leetcode sword offer find the number I (nine) in the sorted array