当前位置:网站首页>如何使用 @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);
}
}
此时就会对 代码中的异常进行拦截 返回到前端,进行展示~
边栏推荐
- Kubernetes帶你從頭到尾捋一遍
- Summary of concurrent full knowledge points
- qt使用QZxing生成二维码
- Qt常用语句备忘
- Detailed comments on MapReduce instance code on the official website
- Global and Chinese markets for ionization equipment 2022-2028: Research Report on technology, participants, trends, market size and share
- Jvm-06-execution engine
- What is embedding (encoding an object into a low dimensional dense vector), NN in pytorch Principle and application of embedding
- 使用JMeter对WebService进行压力测试
- el-switch 赋值后状态不变化
猜你喜欢

Construction of operation and maintenance system

redis缓存穿透,缓存击穿,缓存雪崩解决方案

Introduction to redis master-slave, sentinel and cluster mode

Kubernetes vous emmène du début à la fin

Kubernetes will show you from beginning to end

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

Basic SQL tutorial

视觉上位系统设计开发(halcon-winform)-5.相机
![[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

Jvm-04-runtime data area heap, method area
随机推荐
【日常训练】395. 至少有 K 个重复字符的最长子串
Global and Chinese markets for transparent OLED displays 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese markets for sterile packaging 2022-2028: Research Report on technology, participants, trends, market size and share
Kubernetes带你从头到尾捋一遍
Markdown file titles are all reduced by one level
App global exception capture
Global and Chinese market of postal automation systems 2022-2028: Research Report on technology, participants, trends, market size and share
High quality workplace human beings must use software to recommend, and you certainly don't know the last one
What is machine reading comprehension? What are the applications? Finally someone made it clear
视觉上位系统设计开发(halcon-winform)-5.相机
Mysql报错:[ERROR] mysqld: File ‘./mysql-bin.010228‘ not found (Errcode: 2 “No such file or directory“)
Global and Chinese markets for infrared solutions (for industrial, civil, national defense and security applications) 2022-2028: Research Report on technology, participants, trends, market size and sh
高并发下之redis锁优化实战
使用JMeter对WebService进行压力测试
【Transform】【NLP】首次提出Transformer,Google Brain团队2017年论文《Attention is all you need》
Summary of JVM knowledge points
XWiki安装使用技巧
socket.io搭建分布式Web推送服务器
Reentrantlock usage and source code analysis
视觉上位系统设计开发(halcon-winform)